如何在Laravel中联接多个表?

时间:2020-09-16 17:46:22

标签: laravel

我有3张桌子

1- planes = name, description

2- presidents = id , p_name

3- plane_president = plane_id , president_id

如何与总统和总统飞机一起乘坐飞机?

  $planes = Plane::join('plane_president', 'planes.id', '=', 'plane_president.plane_id')
           ->join('presidents', 'presidents.id', '=', 'plane_president.president_id');

错误:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in order clause is ambiguous (SQL: select * from `planes` inner join `plane_president` on `planes`.`id` = `plane_president`.`plane_id` inner join `presidents` on `presidents`.`id` = `plane_president`.`president_id` order by `id` asc limit 10 offset 0)

2 个答案:

答案 0 :(得分:2)

plane_president是总裁和飞机的数据透视表,您可以在Plane.php模型中声明关系:

    public function presidents()
    {
        return $this->belongsToMany(
                President::class,
                'plane_president',
                'plane_id',
                'president_id');
    }

并像这样使用它:

plane->presidents;

当您想在控制器中检索特定飞机的总统时。

答案 1 :(得分:0)

您有2列名为id的列,错误提示该列模棱两可。 order by id asc limit 10 offset 0在这里,您没有指定要按哪个列订购planes.id或presidents.id