dongyan7876 2013-04-18 10:51
浏览 14
已采纳

通过雄辩的查询在多个表中搜索

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?

  • 写回答

1条回答 默认 最新

  • duanjue9296 2013-04-18 22:58
    关注

    Since they are unrelated tables, you need to do some trickery that's simply too complex for Eloquent to handle, you need to do something similar to the following to join the two queries together, and still be able to do your limit / ordering on the combined queries:

    $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
    ')
    

    NB the above is untested, purely an example of the approach you'll need to take, not sure this will actually work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?