Reputation: 5004
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
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