mercredi 12 octobre 2016

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);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire