S.M_Emamian
S.M_Emamian

Reputation: 17383

where clause inside a relationships - laravel

I have 3 models like this:

WarehousePivotCategory:

 id - warehouse_id - warehouse_category_id

Warehouse:

title

WarehouseCategory:

 title_en

I've created 2 hasOne relationships inside WarehousePivotCategory and they work fine:

  public function Warehouse()
  {
  return $this->hasOne('App\Models\Warehouse','id','warehouse_id');
  }

  public function WarehouseCategory()
  {
  return $this->hasOne('App\Models\WarehouseCategory','id','warehouse_category_id');
  }

in the database I have two records in warehouses table :

  id title
  1 AA
  2 BB

I want to search title in warehouses :

$title = 'AA';



$warehouses = WarehousePivotCategory::with(['warehouse' => function($q) use ($title) {
    $q->where('title', 'like', '%' . $title . '%');
},'WarehouseCategory'])->get();


    foreach ($warehouses as $w)
    {
        echo $w->warehouse->title; // no thing

    }

but it doesn't return any of title of warehouses.

my relationships is correct because below code works fine :

WarehousePivotCategory::with('warehouse','WarehouseCategory')->paginate(10);

Upvotes: 1

Views: 361

Answers (2)

IvanBernatovic
IvanBernatovic

Reputation: 297

I think you're missing get method in your closure. Try it like this:

$warehouses = WarehousePivotCategory::with(['warehouse' => function($q) use ($title) {
$q->where('title', 'like', '%' . $title . '%')->get(); },'WarehouseCategory'])->get();

You can also send array of fields you want to fetch to get method, like this:

    $warehouses = WarehousePivotCategory::with(['warehouse' => function($q) use ($title) {
$q->where('title', 'like', '%' . $title . '%')->get(['id', 'title']); },'WarehouseCategory'])->get();

Upvotes: 1

Ronak Dattani
Ronak Dattani

Reputation: 466

That is wrong. You don't need to use hasone while you have created pivot.You need to use BelongsToMany

class warehouse extends Model{

   public function ware_cat(){
       return $this->BelongsToMany('App\Models\WarehouseCategory');
   }
   public function getWarehouse(){
       $this->with('ware_cat')->get();
   }
}

Pivot table will fetch it so in warehouse model you will get its category and in category model you will get the warehouse same way visa-versa.

Upvotes: 0

Related Questions