vendredi 31 août 2018

Laravel: searching related data

I have models: Student, Tutor, Country.

Main model is Student with code:

public function studentTutors()
{
    return $this->morphedByMany(Tutor::class, 'studentable')
                ->with('tutorAddresses');
}

Then relations.

Tutor:

public function tutorAddresses()
{
   return $this->hasMany(TutorAddress::class, 'tutor_id', 'id')
               ->with('tutorCountry');
}   

TutorAddress:

public function tutorCountry()
{
   return $this->hasOne(Country::class, 'country_id', 'country_id')
               ->where('user_lang', 'en');
}

How do I use it:

$paginator = $student->studentFavouriteTutors()
    ->getQuery()  //for paginate
    ->where(function ($query) use ($searchPhraze) {
        if (strlen(trim($searchPhraze))) {
            return $query
                ->where('username', 'like', '%' . $searchPhraze . '%')
                ->orWhere('firstname', 'like', '%' . $searchPhraze . '%')
                ->orWhere('lastname', 'like', '%' . $searchPhraze . '%');
        }
    })
    ->paginate($pages, $columns, $pageName, $page);

Question:

I am searching in tutors table (Tutor) for user/first/last names.

Is there are way to search for country name from countries table (Country: tutorCountry)? Lets say, table has 'name' column with country names.

If yes, how should $paginator code look like, to get data from countries table?

Same question goes for relation tutorAddresses. Lets say, table has 'city' column with city names.

Is this possible?

Now, I do not use relations for search, and just do joins.

BTW: I tried hasManyThrough relation, but it does not seem to pass data from that 'through' table, so this is not going to work for me. Also, my 'through' relations go a bit too deep for it (unless I do not understand something as far as this relation is concerned).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire