[英]laravel raw join query
我有一个接受原始 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();
}
我如何使用查询构建器的原始连接,就像我可以使用 whereRaw 来处理 where 条件一样?
如果您只是在所有内容上使用原始表达式,请不要打扰查询构建器。
选项 1:利用 PDO
PDO 是 Laravel 使用的底层驱动程序。 要获取 PDO 对象,请运行:
$pdo = DB::connection()->getPdo();
选项 2:运行原始查询
您可以通过 Laravel 运行整个选择,而无需“构建”查询:
DB::select("SELECT * FROM table WHERE ..");
这甚至允许在您需要时进行参数绑定。
在这里,我提出了一些想法,如何让你的方法变得有点通用。 对 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.
注意:我没有将多个连接放在两个表连接中,但您可以使您的方法更通用且更灵活。 我只是试着把一些想法放进我的脑海里。 如果我错了,请纠正我。
参考: Laravel - 加入
味道不好,但有效
\DB::table('data')->join('user', function($join){
$join->on(\DB::raw('( `data`.`user_id` = `user.id` or (`data`.`user_id` is null and `data`.`other_field` is null)) and 1 '),'=',\DB::raw('1'));
})
DB::table('data')->join('users','data.user_id','users.id')->where(~~~)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.