[英]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.