我有三个数据库表:
产品(编号,名称)
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对优势进行排序。
我必须在哪里实现?
最佳答案
对关系使用via
和viaTable
方法将导致两个单独的查询。
您可以在第三个参数中指定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的顺序将被更改。根据您的数据库逻辑,最好将
important
和sort
列移到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/