dongxuan1314 2018-01-04 20:23
浏览 251
已采纳

Laravel - 左边加入“as”参数

I have the following tables:

main
id
user_id
host_id

users
id
room_id

hosts
id
room_id

rooms
id
number

As you can see both users and hosts are connected with table rooms. Unfortunately users.room_number = 1, and hosts.room_number = 2. How can I create a query using leftJoin in laravel to distinguish between users.room_number and hosts.room_number? And then how I can refer to each room_number in my foreach loop?
I have something like this:
MainController.php

$main = DB::table('main')
    ->leftJoin('users', 'users.id', '=', 'main.user_id')
    ->leftJoin('hosts', 'hosts.id', '=', 'main.host_id')
    ->leftJoin('rooms as users_rooms', '=', 'rooms.id', 'users.room_id')
    ->leftJoin('rooms as hosts_rooms', '=', 'rooms.id', 'hosts.room_id')
    ->select('users_rooms.number as u_rooms_number', 'hosts_rooms.number as 
      h_rooms_number')
    ->get();

return view('main.index', ['main' => $index]);

main/index.blade.php

@foreach($main as $element)
    {{ $element->u_rooms_number }}
    {{ $element->h_rooms_number }}
@endforeach

Because of both leftJoin with 'rooms as users_rooms' and 'rooms as hosts_rooms' I get an Error "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rooms.id' in 'on clause'".

  • 写回答

1条回答 默认 最新

  • douqiang7462 2018-01-04 20:41
    关注

    You get the error message, because you join twice on the rooms table. Your on clause therefore cannot identify which table of the two is specified with 'rooms.id'.

    To avoid the conflict you correctly renamed the table joins in your query. Therefore you can use the names as if they were the tables themself.

    ->leftJoin('rooms as users_rooms', '=', 'users_rooms.id', 'users.room_id')
    ->leftJoin('rooms as hosts_rooms', '=', 'hosts_rooms.id', 'hosts.room_id')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?