1

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);
2
  • in the relationship, hasOne have 2nd param as foreign_key and 3rd param as local_key. I think you miss placed them. Please verify with documentation. laravel.com/docs/5.2/eloquent-relationships#one-to-one Commented Oct 12, 2016 at 13:21
  • try this, in the where query change the field name as titles. then it throw an error of whole sql query. In it try can you find something is okay or not. can you understand me..? and also try ManyToMany relationship. Commented Oct 12, 2016 at 13:25

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.