简体   繁体   中英

Yii2 model relation

When I need to use related data in model, I set the pair of keys ( id_item and id ), and the query will be like this -

... ON (category.id = category_translate.id_item) ...

public function getTranslate()
    {
        return $this->hasMany(CategoryTranslate::className(), 
            ['id_item' => 'id'])->indexBy('language');
    }

But what if I need the ON part of query be like this - category.left between 1 and 10 .

How Can I do it?

You should not have a query condition in the ON-part. The ON-part is supposed to link query table to the table you join.

What you actually try to do is, filter your data. But filtering has nothing to do with relations. So, you should keep your relation as is (maybe even drop the indexBy('language') part!) and perform your query like this:

$categories = Category::find()
    ->andWhere(['between', 'left', 1, 10])
    ->joinWith('translate')
    ->indexBy('language');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM