代码之家  ›  专栏  ›  技术社区  ›  Connor Leech

如何使用Laravel query builder跨表选择多个列?

  •  4
  • Connor Leech  · 技术社区  · 8 年前

    我有一个Laravel雄辩的查询,我试图从MySQL表中选择多个列。

        $query = DB::connection('global')
            ->select(
                'mytable.id',
                'mytable.column1',
                'mytable.another_column',
                'mytable.created_at',
                'myothertable.id
            )
            ->from('mytable')
            ->get();
    

    select()函数似乎有三个参数:query、bindings和useReadPdo。上面的查询给了我一个错误:

    {"error":true,"message":"Type error: Argument 1 passed to Illuminate\\Database\\Connection::prepareBindings() must be of the type array, string given" }
    

    如何使用Laravel查询生成器为上述列编写select?

    我以这种方式构造查询,因为我希望在另一个表中有一个连接,如下所示:

        $query = DB::connection('global')
            ->select(
                'mytable.id',
                'mytable.column1',
                'mytable.another_column',
                'mytable.created_at',
                'myothertable.id
            )
            ->from('mytable')
            ->leftJoin('myothertable', function($join){
               $join->on('mytable.id', '=', 'myothertable.id');
            })
            ->get();
    

    如何使用select函数通过雄辩的查询生成器跨表获取多个列?

    1 回复  |  直到 8 年前
        1
  •  5
  •   Prince Lionel N'zi    8 年前

    如何使用Laravel查询生成器为上述列编写select?

    您可以执行以下操作:

    $data = DB::table('mytable')
            ->join('myothertable', 'mytable.id', '=', 'myothertable.mytable_id')
            ->select(
                'mytable.id',
                'mytable.column1',
                'mytable.another_column',
                'mytable.created_at',
                'myothertable.id'
            )
            ->get();
    

    您可以阅读 documentations here