leftJoin仅从第一个表返回列

时间:2015-07-20 07:50:57

标签: mysql yii2

代码在EventUserTypes模型中

$this->find()
        ->select(['event_usertypes.user_type_id' , 'usertypes.name'])
        ->leftJoin('usertypes' , 'event_usertypes.user_type_id = usertypes.id')
        ->where(['event_usertypes.event_id'=>$event_id])
        ->all()

没有错误,它只返回第一个表的列 而不是连接表。它已经有2个小时了,并且在出现问题时已经过多的能量?有什么想法吗?

如果我选择*则返回第一个表的所有列

如果这样做

select(['event_usertypes.user_type_id' , 'usertypes.name'])

它只返回event_usertypes.user_type_id而不是连接表中的名称

请帮帮我

2 个答案:

答案 0 :(得分:1)

尝试执行直接数据库查询,以确保查询结果中可以使用usertypes表:

$query = new \yii\db\Query;
$query->select(['e.user_type_id', 'u.name'])
      ->from('event_usertypes e')
      ->leftJoin('usertypes u', 'e.user_type_id = u.id')  
      ->where(['e.event_id'=> $event_id]);
$command = $query->createCommand();
$resp = $command->queryAll();

查看与您类似的this SO question。此处还有指向Yii documentation的链接,以防这可能有所帮助。

答案 1 :(得分:0)

请尝试这样

$query = new \yii\db\Query;
$query->select(['event_usertypes.user_type_id' , 'usertypes.name'])
        ->from('event_usertypes')
        ->leftJoin('usertypes' , 'event_usertypes.user_type_id = usertypes.id')  
        ->where(['event_id'=> $event_id])->all();
$query->createCommand();