mleontenko
5 months ago

Get related records in query

Posted 5 months ago by mleontenko

I have the following table for records:

record:
	id
	name

and another table that stores related records (user defines related records when creating a new one):

related_records:
	id
	record_id
	related_id

One record can have multiple related records.

In Record model I have defined a relation:

public function related()
    {
        return $this->hasMany('App\Related', 'record_id', 'id');
    }

Now, when I search records by name like this:

Record::query()->where('name', 'LIKE', "%{$searchTerm}%")->get();

I also want to include all related records from results. How can I do this?

Please sign in or create an account to participate in this conversation.