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

标签 activerecord yii2

我有三个数据库表:

产品(编号,名称)

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/

相关文章:

azure - 我如何在 azure 上托管 yii2 框架 Web 应用程序

javascript - 如何在javascript中读取php对象关系(自定义属性)

ruby-on-rails - Rails ActiveRecord Shovel (<<) 运算符

ruby-on-rails - Rails 4 ActiveRecord has_many 通过关系

ruby-on-rails - Rails 4 按虚拟属性排序

php - Yii2在beforeSave()和update(或insert)中检查模型三个字段的存在组合

php - 调用未定义的方法 Symfony\Component\DomCrawler\Crawler::rewind()

ruby-on-rails - 如何将 boolean 逻辑语句与事件记录链接起来?

ruby-on-rails - Rails 查询外部函数

database - yii2 使用 ActiveRecord 批量插入