Yii2 Activerecord get fields from junction table and order by according to them

*爱你&永不变心* 提交于 2019-12-06 16:13:47

Finally I have found a solution. It depends on findBySql method. I'm going to use the above SQL query regarded in Update 2 -just I have removed some selected fields to be suitable for my current task-.

public function actionUnitsJson($id){    
$sql = 'SELECT units.id, units.title 
    FROM units
     Left JOIN item_units AS iu
      ON iu.item_id = :id AND iu.unit_id = units.id 
    WHERE 
        units.id = iu.unit_id 
    ORDER BY iu.weight DESC;';

          $units = \common\models\Units::findBySql($sql,[':id' => $id])->asArray()->all();
    return Json::encode($units);
}

You need fields or extraFields in your ActiveRecord model with asArray.

Example:

/**
 * @return array
 */
public function fields()
{
    return [
        'itemUnit', //will get getItemUnit method
    ];
}

or

/**
 * @return array
 */
public function extraFields()
{
    return [
        'itemUnits', //it is relation name
    ];
}

Usage:

$model->toArray(); //will contains fields and extra fields relations
... sort array & return

By default, yii\base\Model::fields() returns all model attributes as fields, while yii\db\ActiveRecord::fields() only returns the attributes which have been populated from DB.

You can override fields() to add, remove, rename or redefine fields. The return value of fields() should be an array. The array keys are the field names, and the array values are the corresponding field definitions which can be either property/attribute names or anonymous functions returning the corresponding field values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!