联盟后搜索查询

时间:2016-05-26 13:48:20

标签: mysql datatable laravel-5.2 query-builder

我有这种方法来处理Bootstrap Datatables的服务器端数据

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);
}

我猜DataTables所做的是在提供的查询上执行WHERE LIKE搜索。 问题是我试图进行搜索,它返回随机结果。答案here表明我必须在UN子句中嵌入UNION,比如

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'},
        ]
    });

});

1 个答案:

答案 0 :(得分:0)

像这样使用它将mysql查询整体放在引号中,如下所示,

DB:raw('SELECT *   FROM(SELECT * FROM TableA         联盟         SELECT * FROM TableB        )AS U.  在哪里U.Col1 = ...') - &gt; get();

这将产生预期的结果。