2

I have two tables: posts and pages. Based on the keyword, I want to search different columns of the two tables for the occurrence of keyword. The two tables do not have related content.

I have written two queries one for each table. Following are the queries:

$result1 = Post::where('title_en', 'LIKE', '%' . $keyword . '%')
                ->or_where('title_np', 'LIKE', '%' . $keyword . '%')
                ->order_by('id', 'desc')
                ->paginate(10);

$result2 = Page::where('title', 'LIKE', '%' . $keyword . '%')
                ->or_where('content', 'LIKE', '%' . $keyword . '%')
                ->order_by('id', 'desc')
                ->paginate(10);

The above queries return two different Laravel\Paginator object. But I want a single Laravel\Paginator object so that a single pagination is displayed on the page which works for both the queries or on a single query which achieves the functionality of both the above queries. How would I be able to do that?

4

1 回答 1

1

由于它们是不相关的表,你需要做一些对 Eloquent 来说太复杂的技巧,你需要做一些类似于以下的事情来将两个查询连接在一起,并且仍然能够对组合进行限制/排序查询:

$results = DB::query('SELECT id, title FROM ( 
SELECT id, title FROM `post` where `title_np` LIKE "%'.$keyword.'%" OR `title_en` LIKE "%'.$keyword.'%"
UNION ALL
SELECT id, title FROM `page` where `title` LIKE "%'.$keyword.'%" OR `content` LIKE "%'.$keyword.'%"
) temp_table
ORDER BY `id` desc
LIMIT 0, 10
')

注意以上内容未经测试,纯粹是您需要采取的方法的一个示例,不确定这是否真的有效。

于 2013-04-18T22:58:10.817 回答