2016-05-26 193 views
1

後,我有這樣的方法來處理服務器端數據的引導數據表搜索查詢聯盟

public function datatable(Request $request) 
{ 
    $organizations = DB::table('organizations') 
     ->join('customers', function ($join) 
     { 
      $join->on('organizations.id', '=', 'customers.customer_id') 
       ->where('customers.customer_class', '=', 'Organization'); 
     }) 
     ->select([ 
      'customers.id', 
      'organizations.name', 
     ]); 

    $contacts = DB::table('contacts') 
     ->join('customers', function ($join) 
     { 
      $join->on('contacts.id', '=', 'customers.customer_id') 
       ->where('customers.customer_class', '=', 'Contact'); 
     }) 
     ->select([ 
      'customers.id', 
      'contacts.name', 
     ]); 

    $customers = $organizations->union($contacts); 

    return Datatables::of($customers) 
     ->editColumn('name', function($customers) { 
      return '<a href="'.route('customers.show', $customers->id).'">'.$customers->name.'</a>'; 
     }) 
     ->make(true); 
} 

我猜數據表的作用是執行WHERE上提供的查詢LIKE搜索。 問題是,我試圖執行搜索whenecer,它返回隨機結果。答案here表明,我必須有嵌入UNION在FROM子句中,像

SELECT * 
    FROM (SELECT * FROM TableA 
     UNION 
     SELECT * FROM TableB 
     ) AS U 
WHERE U.Col1 = ... 

但我不能換我的頭在Laravel查詢生成器如何和身邊向。

如果它是相關的,這裏的JS代碼

$(function() { 
    $('#customer-table').DataTable({ 
     processing: true, 
     serverSide: true, 
     bfilter: false, 
     ajax: "{{route('customers.datatable')}}", 
     columns: [ 
      { data: 'name'}, 
     ] 
    }); 

}); 
+0

您能否顯示您收到的錯誤請 – RiggsFolly

+0

沒有錯誤。問題是搜索結果與搜索字符串不一致 –

回答

0

使用它這樣是把MySQL查詢作爲整體在下文報價,

DB:原料(「SELECT * FROM(SELECT * FROM表A UNION SELECT * FROM TableB )AS U WHERE U.Col1 = ...') - > get();

這會給出想要的結果。

+0

在Laravel 5.2中,類'Illuminate \ Database \ Query \ Expression'沒有方法get'https://laravel.com/api/5.2/Illuminate/Database/ Query/Expression.html –

+0

你可以在這裏查看原始表達式https://laravel.com/docs/5.2/queries –

+0

'DB:raw'在這裏不起作用。 PDO是答案 –