joinWith 多表查询,如何给表名在sql里定义临时名 [ 2.0 版本 ]
这代码实现的sql是这样的,但是我要对admin表关联两次,运行就会报错
【[Err] 42000 - [SQL Server]FROM 子句中的对象 "dbo.sp__admin" 和 "dbo.sp__admin" 具有相同的表现名称。请使用相关名称来区分它们。】
SELECT [dbo].[sp__log].* FROM [dbo].[sp__log] LEFT JOIN [dbo].[sp__users] ON [dbo].[sp__log].[uid] = [dbo].[sp__users].[id] LEFT JOIN [dbo].[sp__admin] ON [dbo].[sp__log].[aid] = [dbo].[sp__admin].[id] LEFT JOIN [dbo].[sp__admin] ON [dbo].[sp__log].[audit_aid] = [dbo].[sp__admin].[id] WHERE (dbo.sp__log.[belong] = 'Paycheck')
如果把sql改成:
SELECT [dbo].[sp__log].* FROM [dbo].[sp__log]
LEFT JOIN [dbo].[sp__users] ON [dbo].[sp__log].[uid] = [dbo].[sp__users].[id]
LEFT JOIN [dbo].[sp__admin] a ON [dbo].[sp__log].[audit_aid] = a.[id]
LEFT JOIN [dbo].[sp__admin] b ON [dbo].[sp__log].[aid] = b.[id]
WHERE (dbo.sp__log.[belong] = 'Paycheck')
就是两次查询admin分别给重命名,这样就能查询成功,但是在代码里怎么实现呢
共 5 个回答
-
测试模型
User
//... public function getCount() { return $this->hasOne(UserCount::class, ['user_id' => 'id']); } public function getSetting() { return $this->hasMany(UserSetting::class, ['user_id' => 'id']); } //...
测试代码
echo User::find() ->joinWith('count as a') ->joinWith('setting as b') ->createCommand() ->getRawSql();
输出sql
SELECT `user`.* FROM `user` LEFT JOIN `user_count` `a` ON `user`.id = a.user_id LEFT JOIN `user_setting` `b` ON `user`.id = b.user_id
仅供参考 :)
-
qqa4560354 回答于 2017-12-22 11:39 举报
Controller
$userdata = Us::find()->select(['user.id','user.username','user.room_id','room.name']) ->where($where) ->andWhere("user.id=$user_id") ->joinWith('room');
Model
public function getRoom(){ return $this->hasOne(Room::className(), ['id'=>'room_id']); }
jsnnid
注册时间:2017-11-23
最后登录:2018-01-12
在线时长:1小时19分
最后登录:2018-01-12
在线时长:1小时19分
- 粉丝0
- 金钱10
- 威望0
- 积分20