简体   繁体   English

Yii2 模型关系

[英]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 -当我需要在模型中使用相关数据时,我设置了一对键( id_itemid ),查询将是这样的——

... 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 .但是,如果我需要查询的ON部分像这样 - category.left between 1 and 10怎么办。

How Can I do it?我该怎么做?

You should not have a query condition in the ON-part.在 ON 部分中不应有查询条件。 The ON-part is supposed to link query table to the table you join. ON 部分应该将查询表链接到您加入的表。

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:所以,你应该保持你的关系(甚至可能删除indexBy('language')部分!)并像这样执行你的查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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