gpt4 book ai didi

activerecord - ActiveRecord通过表的位置和顺序

转载 作者:行者123 更新时间:2023-12-03 13:18:15 25 4
gpt4 key购买 nike

我有三个数据库表:

产品(编号,名称)

product_has_adv(产品,优势,分类,重要)

优势(ID,文字)

在ProductModel中,我定义了以下内容:

public function getAdvantages()
{
return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
->viaTable('product_has_advantage', ['product' => 'id']);
}


我得到的好处没有任何问题。

但是现在我需要添加一个where product_has_advantage.important = 1子句,并且还要按product_has_advantage-table中的sort-columen对优势进行排序。

我必须在哪里实现?

最佳答案

对关系使用viaviaTable方法将导致两个单独的查询。

您可以在第三个参数中指定callable,如下所示:

public function getAdvantages()
{
return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
->viaTable('product_has_advantage', ['product' => 'id'], function ($query) {
/* @var $query \yii\db\ActiveQuery */

$query->andWhere(['important' => 1])
->orderBy(['sort' => SORT_DESC]);
});
}


将应用 important过滤器,但不会进行排序,因为它发生在第一个查询中。结果, IN语句中id的顺序将被更改。

根据您的数据库逻辑,最好将 importantsort列移到 advantage表中。

然后只需添加条件并排序到现有方法链即可:

public function getAdvantages()
{
return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
->viaTable('product_has_advantage', ['product' => 'id'])
->andWhere(['important' => 1])
->orderBy(['sort' => SORT_DESC]);
}

关于activerecord - ActiveRecord通过表的位置和顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27690401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com