2015-10-13 91 views
8

只有几列在控制我有:Yii2选择关联模型

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

我怎么能控制哪些列数据是从“用户”关系中获得的吗?我目前得到的所有列都不好,因为这些数据以JSON格式发送到Angular。 现在我必须循环低谷$ items和filer出我不想发送的所有列。

回答

12

您应该简单地修改相关的查询是这样的:

$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

+1

我得到这个错误:PHP的通知 - 警予\基地\ ErrorException 未定义指数:USER_ID什么会是什么? – Ljudotina

+1

哦,好吧,我知道了....我必须从相关表中选择“user_id”列。 – Ljudotina

+1

为了它的工作原理,您还需要选择相关类的链接字段。在这种情况下,它将是'User'模型的'user_id':'$ query-> select('user_id,col1,col2');'。 –

0

您的代码应该走这条路。

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