ActiveRecord where and order on via-table

前端 未结 8 725
南旧
南旧 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 12:58

    First you need to create a model named ProductHasAdv for junction table (product_has_adv) using CRUD.

    Then create relation in product model and sort it:

      public function getAdvRels()
        {
            return $this->hasMany(ProductHasAdv::className(), ['product' => 'id'])->
            orderBy(['sort' => SORT_ASC]);;
        }
    

    Then create second relationship like this:

    public function getAdvantages()
    {
        $adv_ids = [];
        foreach ($this->advRels as $adv_rel)
            $adv_ids[] = $adv_rel->advantage;
        return $this->hasMany(Advantage::className(), ['id' => 'advantage'])->viaTable('product_has_adv', ['product' => 'id'])->orderBy([new Expression('FIELD (id, ' . implode(',', $adv_ids) . ')')]);
    }
    

    This will sort final result using order by FIELD technique.

    Don't forget to add:

    use yii\db\Expression;
    

    line to head.

提交回复
热议问题