如何为 laravel 中的给定输入搜索两个表
How to search two tables for the given input in laravel
在我的应用程序中,有 article
和 news
table。我知道我可以在新闻 table 或文章中搜索匹配的标题,
只需做类似的事情:
$query = $request['search'];
$searchResult= DB::table('article')->where('title', 'LIKE', '%$query%')
->orderBy('created_at', 'desc')->paginate(10);
或
$searchResult= DB::table('news')->where('title', 'LIKE', '%$query%')
->orderBy('created_at', 'desc')->paginate(10);
但我想做的是搜索它们和 return 一些关于它们的信息以及 reuslt 类型是什么,在新闻和文章方面。而不是通过 created_at
对它们进行排序,就好像它们在同一个 table 中一样。
Laravel 5.4
如果您希望每页显示 10 条新闻和 10 篇文章,您可以这样做。但在这种情况下,您需要 manually create paginator。
加载数据:
$articles = DB::table('article')
->where('title', 'like', '%$query%')
->latest()
->skip(0)
->take(10)
->get();
$news = DB::table('news')
->where('title', 'like', '%$query%')
->latest()
->skip(0)
->take(10)
->get();
然后合并结果:
$merged = $articles->merge($news);
如果需要,则按日期排序:
$merged = $merge->sortByDesc('created_at');
在我的应用程序中,有 article
和 news
table。我知道我可以在新闻 table 或文章中搜索匹配的标题,
只需做类似的事情:
$query = $request['search'];
$searchResult= DB::table('article')->where('title', 'LIKE', '%$query%')
->orderBy('created_at', 'desc')->paginate(10);
或
$searchResult= DB::table('news')->where('title', 'LIKE', '%$query%')
->orderBy('created_at', 'desc')->paginate(10);
但我想做的是搜索它们和 return 一些关于它们的信息以及 reuslt 类型是什么,在新闻和文章方面。而不是通过 created_at
对它们进行排序,就好像它们在同一个 table 中一样。
Laravel 5.4
如果您希望每页显示 10 条新闻和 10 篇文章,您可以这样做。但在这种情况下,您需要 manually create paginator。
加载数据:
$articles = DB::table('article')
->where('title', 'like', '%$query%')
->latest()
->skip(0)
->take(10)
->get();
$news = DB::table('news')
->where('title', 'like', '%$query%')
->latest()
->skip(0)
->take(10)
->get();
然后合并结果:
$merged = $articles->merge($news);
如果需要,则按日期排序:
$merged = $merge->sortByDesc('created_at');