user1690835 user1690835 - 5 months ago 44
PHP Question

Laravel join two tables using model

I am developing a laravel application in which I want to join two tables and get the result. I have two models, first one is category.php which is given below.

class Category extends Model implements AuthenticatableContract, CanResetPasswordContract
{


public function products()
{
return $this->hasMany('App\Products', 'product_category_id');
}



}


Second one is products.php

class Products extends Model implements AuthenticatableContract, CanResetPasswordContract
{


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

}


Now when I write the query
Category::where('status', 1)->get()
it is giving the result. But when I try to join the tables using
Category::find(1)->products()->where('status', 1)->get();
it is giving null result. Please help

Answer

The correct way to get products relation and filter the results is:

Category::where('status', 1)->with(['products' => function ($query) {
   $query->where('name', 'like', '%search_string%');
}])->get();