Yii2 Select 只有几列来自相关模型

Yii2 Select only few columns from related model

在控制器中我有:

public function actionGetItems()
{
    $model = new \app\models\WarehouseItems;
    $items = $model->find()->with(['user'])->asArray()->all();
    return $items;
}

在 WarehouseItem 模型中,我有标准(由 gii 创建)关系声明:

public function getUser()
{
    return $this->hasOne('\dektrium\user\models\User', ['user_id' => 'user_id']);
}

如何控制从 "user" 关系中获取哪些列数据?我目前得到的所有列都不好,因为数据以 JSON 格式发送到 Angular。 现在我必须遍历 $items 并过滤掉我不想发送的所有列。

您应该像这样简单地修改关系查询:

$items = \app\models\WarehouseItems::find()->with([
    'user' => function ($query) {
        $query->select('id, col1, col2');
    }
])->asArray()->all();

阅读更多:http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail

你的代码应该这样写。

public function actionGetItems()
{
    $items = \app\models\WarehouseItems::find()
        ->joinWith([
             /*
              *You need to use alias and then must select index key from parent table
              *and foreign key from child table else your query will give an error as
              *undefined index **relation_key**
              */
            'user as u' => function($query){
                $query->select(['u.user_id', 'u.col1', 'u.col2']);
            }
        ])
        ->asArray()
        ->all();

    return $items;
}

内部 WarehouseItem 模型

/**
 * @return ActiveQuery
 */
public function getUser()
{
    $query = User::find()
        ->select(['id', 'col1', 'col2'])
        ->where([
            'id' => $this->user_id,
        ]);
    /** 
     * Default hasOne, setup multiple for hasMany
     * $query->multiple = true;
     */
    return $query;
}