Laravel 原始连接查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46566920/
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
laravel raw join query
提问by Chris
I have a function that accepts raw where conditions and joins:
我有一个接受原始 where 条件并加入的函数:
query('data',['fieldA','fieldB'], 'fieldA > 10 AND fieldB < 20', 'LEFT JOIN users ON data.user_id = users.id');
function query($table, $keys = [], $where = '', $joins = '') {
$query = DB::table($table)->select($keys);
if(!empty($where)) {
$query=$query->whereRaw($where);
}
if(!empty($joins)) {
$query=$query->?????????????
}
return $query->get();
}
How do I use the raw join with the query builder the way I can use whereRaw for the where condition?
我如何使用查询构建器的原始连接,就像我可以将 whereRaw 用于 where 条件一样?
回答by Devon
Don't bother with the query builder if you're just using raw expressions on everything.
如果您只是在所有内容上使用原始表达式,请不要打扰查询构建器。
Option 1: Utilize PDO
选项 1:利用 PDO
PDO is the underlying driver used by Laravel. To get the PDO object, run:
PDO 是 Laravel 使用的底层驱动程序。要获取 PDO 对象,请运行:
$pdo = DB::connection()->getPdo();
Option 2: Run raw queries
选项 2:运行原始查询
You can run entire selects through Laravel without "building" a query:
您可以通过 Laravel 运行整个选择,而无需“构建”查询:
DB::select("SELECT * FROM table WHERE ..");
This even allows parameter binding when you need it.
这甚至允许在您需要时进行参数绑定。
回答by webDev
Here I have put some idea how can you make your method little bit generic. Do same thing for where clause and other part of the query.
在这里,我提出了一些想法,如何让你的方法变得有点通用。对 where 子句和查询的其他部分做同样的事情。
query('data',['fieldA','fieldB'], 'fieldA > 10 AND fieldB < 20', 'LEFT', 'users', 'data.user_id','users.id');
function query($table, $keys = [], $where = '', $join_type = 'LEFT', $join_table='', $join_field1='', $join_field2='') {
$query = DB::table($table)->select($keys);
if(!empty($where)) {
$query=$query->whereRaw($where);
}
if(!empty($joins)&&!empty($join_type)&&$join_type=='LEFT') {
$query=$query->leftJoin($join_table, $join_field1, '=', $join_field2)
}
if(!empty($joins)&&!empty($join_type)&&$join_type=='INNER') {
$query=$query->join($join_table, $join_field1, '=', $join_field2)
}
///and so on
return $query->get();
}
//But you can make this method more generic, I just put some idea so that you can make this method more flexible
//I did not take a look at your other part of the method though.
Note:I did not put multiple joins only two table joins but you can make your method more generic form and more flexible. I just tried to put some idea that comes into my mind. If I am wrong then correct me please.
Reference:Laravel - Joins
注意:我没有将多个连接放在两个表连接中,但是您可以使您的方法更通用且更灵活。我只是试着把一些想法放进我的脑海里。如果我错了,请纠正我。
参考:Laravel - 加入
回答by uiuifree
DB::table('data')->join('users','data.user_id','users.id')->where(~~~)