ActiveRecord的地点和顺序通过表 [英] ActiveRecord where and order on via-table

查看:119
本文介绍了ActiveRecord的地点和顺序通过表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个数据库表:

产品(编号,名称)

product_has_adv(产品优势,排序,重要的)

product_has_adv (product,advantage,sort,important)

优势(ID,文字)

在产品型号我定义的:

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

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

I get the advantages without any problems.

但现在我需要的排序columen在product_has_advantage表添加一个,其中product_has_advantage.important = 1 clausel也进行排序的优势。

But now I need to add a where product_has_advantage.important = 1 clausel and also sort the advantages by the sort-columen in the product_has_advantage-table.

如何以及在哪里我要实现它?

How and where I have to realize it?

推荐答案

使用通过 viaTable 方法有关系会造成两个单独的查询。

Using via and viaTable methods with relations will cause two separate queries.

您可以指定调用在这样的第三个参数:

You can specify callable in third parameter like this:

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]);
        });
}

过滤重要将被应用,但那种不会因为它发生在第一个查询。其结果是ID的顺序语句将被改变。

The filter by important will be applied, but the sort won't since it's happen in first query. As a result the order of ids in IN statement will be changed.

根据数据库的逻辑也许是更好的移动重要排序优势表。

Depending on your database logic maybe it's better to move important and sort columns to advantage table.

然后,只需添加条件和排序,以现有的方法链:

Then just add condition and sort to the existing method chain:

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

这篇关于ActiveRecord的地点和顺序通过表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆