简体   繁体   中英

laravel raw join query

I have a function that accepts raw where conditions and joins:

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?

Don't bother with the query builder if you're just using raw expressions on everything.

Option 1: Utilize PDO

PDO is the underlying driver used by Laravel. To get the PDO object, run:

$pdo = DB::connection()->getPdo();

Option 2: Run raw queries

You can run entire selects through Laravel without "building" a query:

DB::select("SELECT * FROM table WHERE ..");

This even allows parameter binding when you need it.

https://laravel.com/docs/5.5/database

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.

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

Haven't good smell but works

    \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(~~~)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM