我想在laravel 5.2 Eloquent格式中隐藏简单查询

时间:2016-10-18 12:32:59

标签: laravel laravel-5.2

我有这个SQL查询,我想转换为Eloquent:

 $query = "(SELECT name, Heading, 'msg' as type FROM tbl_cms WHERE name LIKE '%" . 
       $keyword . "%' OR Heading LIKE '%" . $keyword ."%') 
       UNION
       (SELECT name, channel, 'topic' as type FROM  tbl_dramas WHERE name LIKE '%" . 
       $keyword . "%' OR channel LIKE '%" . $keyword ."%')";

我当前的Eloquent查询如下所示:

$keyword = $request->get("term");
if ($keyword != '') {
    $query->where(function ($query) use ($request) {
        $query->where("name", "LIKE","%$keyword%")
            ->orWhere("Heading", "LIKE", "%$keyword%");
    });
}
return view('search', ['title' => 'search' ,'query' => $query]);

如何成功转换?

3 个答案:

答案 0 :(得分:0)

$first = DB::table('tbl_cms')
            ->select('name', 'Heading', 'msg as type')
            ->where('name', 'like', $keyword.'%')
            ->orwhere('Heading', 'like', $keyword.'%');

$data = DB::table('tbl_dramas')
            ->select('name', 'channel', 'topic as type')
            ->where('name', 'like', $keyword.'%')
            ->orwhere('channel', 'like', $keyword.'%')
            ->union($first)
            ->get();

像这样的东西

答案 1 :(得分:0)

试试这个:

$query1 = \DB::table('tbl_cms')
    ->select(\DB::raw('name, Heading, msg AS type'))
    ->where('name', 'LIKE', '%'.$keyword.'%')
    ->orWhere('Heading', 'LIKE', '%'.$keyword.'%');

$query2 = \DB::table('tbl_dramas')
    ->select(\DB::raw('name, channel, topic AS type'))
    ->where('name', 'LIKE', '%'.$keyword.'%')
    ->orWhere('channel', 'LIKE', '%'.$keyword.'%');

$result = $query1->union($query2)->get();

答案 2 :(得分:0)

$keyword = '%'.\Input::get('q').'%';

$query1 = \DB::table('tbl_cms')
    ->select(\DB::raw("name, Heading, 'msg' as 'type'"))
    ->where('name', 'LIKE', $keyword)
    ->orWhere('Heading', 'LIKE', $keyword);

$query2 = \DB::table('tbl_dramas')
    ->select(\DB::raw("name, channel, 'topic' as 'type'"))
    ->where('name', 'LIKE', $keyword)
    ->orWhere('channel', 'LIKE', $keyword);

$results = $query1->union($query2)->get();