S
S
Sergey Bard2018-03-15 22:41:30
Yii
Sergey Bard, 2018-03-15 22:41:30

How to make a selection using hasMany?

Hello. I can't figure out how to do it.
In general, I have a product_id and I need to get a shop_id, so I sketched an example from the database,
5aaac9dbe5004013734382.jpeg
i.e. go in order from left to right through the tables in order, choosing the necessary fields, I try to do this, in the product table model I call getshopCity ()

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

    public function getProductCity()
    {
        return $this->hasMany(shopCity::className(),['shop_city_id'=>'shop_city_id'])->via('productPrice');
    }

    public function getshopCity()
    {
        return $this->hasMany(shop::className(),['shop_id'=>'shop_id'])->via('productCity');
    }

everything works only if the whole link is there, but if, for example, I have a product in the product, but it is not in the shop_product_price table, then the link is broken, so to speak, and it says to me that there is no shop_city_id, how can I make it skip it when there is no corresponding record in the shop_product_price table and selected only records with a full link,
tried to replace getProductPrice ()
return $this->hasMany(shopProductPrice::className(),['shop_Product_id'=>'shop_Product_id']);

to a simple selection from the database with the condition that the product_id is not equal to NULL, but it doesn’t work at all,
tell me, maybe I’m doing something wrong?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-03-16
@serg_small_developer

Firstly: You unsuccessfully chose the names of the tables and fields in them (and, accordingly, the models)
1. shop_city - in the comment you write that this is a list of branches, and judging by the name, just a link table. It's better to replace its name with something more suitable, for example (the first thing that came to mind): shop_office
2. shop_product_price - by the name you can say that these are the prices of goods in the store, but if you delve into it, it turns out that these are the prices of goods in the STORE BRANCHES .
secondly: the link that selects the store should not be in the Product model, but in the branch model, and the names of the links themselves are not chosen well - they only confuse.
Those. in the Goods model there must be a link that selects branches, in the branch model - a link that selects a store
or if you need to display products that have all links

Product::find()->joinWith(['<название связи с филиалом>.<название связи филиала с магазином>'], true, 'RIGHT JOIN')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question