ActiveRecord where and order on via-table

前端 未结 8 699
南旧
南旧 2020-12-16 12:22

I have three database table:

product (id, name)

product_has_adv (product,advantage,sort,important)

advantage (id, text)

In ProductModel I def

8条回答
  •  醉梦人生
    2020-12-16 13:17

    Using viaTable methods with relations will cause two separate queries, but if you don't need link() method you can use innerJoin in the following way to sort by product_has_advantage table:

    public function getAdvantages()
    {
        $query = AdvantageModel::find();
        $query->multiple = true;
        $query->innerJoin('product_has_advantage','product_has_advantage.advantage = advantage.id');
        $query->andWhere(['product_has_advantage.product' => $this->id, 'product_has_advantage.important' => 1]);
        $query->orderBy(['product_has_advantage.sort' => SORT_DESC]);
        return $query;
    }
    

    Note than $query->multiple = true allows you to use this method as Yii2 hasMany relation.

提交回复
热议问题