W
W
WebDev2016-03-14 18:34:49
Laravel
WebDev, 2016-03-14 18:34:49

Communication via Laravel table?

Tell me, there are 3 models:
Purchase, Product, Category
Purchase and Category are connected through Product (Product has purchase_id and category_id properties).
How do I get all Purchases of a certain category? More precisely, how to describe the relationship? hasManyThrough is not suitable, because where the models must be linked in a chain.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-03-14
@kirill-93

For example, we have a structure like this

product table:
id, name, purchase_id, category_id category
table:
id, name
purchase table:
id, total

In the Product model:
public function purchase(){
    $this->hasMany('Purchase');
}

In this case, you can get all purchase categories using whereHas.
Sample code (not tested):
$purchases = Product::with('purchase')->whereHas('category', function($query){
   $query->where('id', 1);
})->get()->lists('purchase');

But the structure is initially wrong. You need to rethink it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question