A
A
alex4answ2019-04-05 11:30:03
Yii
alex4answ, 2019-04-05 11:30:03

Condition for hasMany with linked table?

Good afternoon, there are 2 tables:
1. Product (id, name, hasDelivery)
2. Delivery (id, product_id, text)
I need to get all products + delivery (only for products with hasDelivery = 1), how to implement this?
Now I have

public function getDelivery(){
        return $this->hasMany(Delivery::className(), ['product_id' => 'id']);
    }

That is, now delivery information is searched for all goods, although for most it is not there, and cannot be. I tried in different ways, and add a condition to hasMany()->where, but as if there is no connection with the parent table
How to add a condition so that Delivery is searched only for those goods that have hasDelivery = 1 ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2019-04-11
@alex4answ

If there is no delivery, then delivery will also contain an empty array, I would not even create the hasDelivery column, since it is redundant, by the presence of related rows, it is clear whether hasDelivery or not. So I don't see the problem, but you can try this:

public function getDelivery(){
        return $this->hasDelivery ? $this->hasMany(Delivery::className(), ['product_id' => 'id']) : null;
}

if of course in hasDeliveryboolean, etc.
But you use with so there all the same 1 request all communications are drawn. Why bother here? In any case, there will be 2 requests. 1 picks up the product/products, 2nd links to it/them. So we throw out the hasDelivery column and replace it with a method in the model. Something like:
public function getDelivery(){
        return $this->hasMany(Delivery::className(), ['product_id' => 'id']);
}

public function hasDelivery(){
        return count($this->delivery > 0);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question