Mojtaba
Mojtaba

Reputation: 5004

laravel 5.2 search in related entity

Suppose I have a Model called 'Commodity' which has category_id belongs to a category.

In Commodity.php I defined this relationship:

public function category(){
    return $this->belongsTo('App\Category');
}

Now, I want to find the commodities which their category name include 'glass'

I tried this:

$items = Commodity::orderBy('id', 'desc')->category()->where('title', 'LIKE', '%glass%');

But it populates this error:

Call to undefined method Illuminate\Database\Query\Builder::category()

Upvotes: 1

Views: 364

Answers (1)

Artyom Sokolov
Artyom Sokolov

Reputation: 2405

Please read official documentation that covers querying relations.

Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:

$users = App\User::with(['posts' => function ($query) {
   
    $query->where('title', 'like', '%first%');

}])->get();

So, regarding your question I'd suggest to try next:

$commodities = App\Commodity::with(['category' => function ($query) {
    
    $query->where('title', 'like', '%glass%');

}])->orderBy('id', 'desc')->get();

Upvotes: 2

Related Questions