写代码在laravel中连接相同的表

时间:2017-06-04 17:48:48

标签: mysql laravel left-join

我有2张桌子

Table 1: farm has columns id, name, id_tech, id_manager
Table 2: User has columns: id, name

我在mysql中运行以下语句:

 SELECT eco_farm.id, eco_farm.name as farmname, A.name as manager, 
       B.name as tech 
 FROM eco_farm 
 LEFT JOIN eco_user A ON A.id = eco_farm.id_manager 
 LEFT JOIN eco_user B ON B.id = eco_farm.id_tech

结果是 enter image description here

但是我不知道如何在laravel中编写如何在laravel中检索数据的代码。愿你帮助我。谢谢

1 个答案:

答案 0 :(得分:0)

这是使用查询构建器。

$result = \DB::table('eco_farm')
    ->leftJoin('eco_user as A', 'A.id', '=', 'eco_farm.id_manager')
    ->leftJoin('eco_user as B', 'B.id', '=', 'eco_farm.id_tech')
    ->selectRaw('eco_farm.id, eco_farm.name as farmname, A.name as manager, B.name as tech')
    ->get();

查看文档以获取更多信息和示例https://laravel.com/docs/5.4/queries