如何使用 Laravel 查询生成器跨表选择多列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48653190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I select multiple columns across tables with Laravel query builder?
提问by Connor Leech
I have a Laravel Eloquent query where I am trying to select multiple columns from a MySQL table.
我有一个 Laravel Eloquent 查询,我试图从 MySQL 表中选择多个列。
$query = DB::connection('global')
->select(
'mytable.id',
'mytable.column1',
'mytable.another_column',
'mytable.created_at',
'myothertable.id
)
->from('mytable')
->get();
It looks like the select() function takes three arguments: query, bindings and useReadPdo. The above query gives me an error:
看起来 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" }
How do I write a select with Laravel query builder for the above columns?
如何使用 Laravel 查询构建器为上述列编写选择?
I am structuring the query in this way, because I am looking to have a join across another table like so:
我正在以这种方式构建查询,因为我希望在另一个表中进行连接,如下所示:
$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();
How do I use the select function to grab multiple columns across tables with Eloquent query builder?
我如何使用 select 函数通过 Eloquent 查询构建器跨表抓取多个列?
采纳答案by Prince Lionel N'zi
How do I write a select with Laravel query builder for the above columns?
如何使用 Laravel 查询构建器为上述列编写选择?
You can do:
你可以做:
$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();
You can read the documentations here