1

Item Model:

public function item_makes(){
     return $this->hasMany(ItemMake::class,'item_id','id');
}

In ItemMake Model :

public function make(){
    return $this->belongsTo(Make::class,'make_id','id');
}

I need to get array of all make based on item_id. How to achieve this? Thanks in Advance.

0

3 Answers 3

2

This worked for me.

$item = Item::findOrFail(1)
         ->item_makes()
         ->with('make')
         ->get()
         ->pluck('make')
         ->flatten()
         ->toArray();
Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this:

Item::findOrFail(1)
    ->with('item_makes.make')
    ->get()
    ->pluck('make')
    ->flatten()
    ->toArray()

3 Comments

Thank you so much Sir :)
You can also use whereHas method from Make model. This way, you wouldn't need to flatten or pluck.
I agree, but then you would also need a subquery to only get makes that belong to item_makes of an item with the given id.
1

Try wherehas method something like this

$makes = Make::whereHas('item_makes', function ($query) use($item_id) {
   $query->where('item_id',  $item_id);
})->get();

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.