【问题标题】:Combining two different with no relationship DB table query in laravel for pagination在laravel中结合两个不同的无关系数据库表查询进行分页
【发布时间】:2019-07-06 15:51:42
【问题描述】:

我的数据库中有两个不相关的表,我需要将它们合并,以便将其放在我的搜索视图中,但我不知道是否可能。

这是我的代码。 newsseason 表不相关,但它们具有相似的列,我试图将它们放入一个对象中以便于分页。有可能吗?

$search = $request->search;
    $nresult = DB::table("news")
                ->select("news.news_id as id","news.title as title", "news.name_key as key", "news.content", "news.image", "news.thumb", DB::raw("'news' as type"))
                ->where("news.status", "=", 1)
                ->Where("news.title", "like", "%".$search."%")
                ->orWhere("news.content", "like", "%".$search."%")
                ->orWhere("news.variables", "like", "%".$search."%")
                ->orWhere("news.categories", "like", "%".$cat_id."%")
                ->orderBy("title", "asc")
                ->paginate(5);

            $sresult = DB::table("season")
                ->select("season.season_id as id","season.name as title", "season.key as key", "season.content", "season.image", "season.thumb", DB::raw("'season' as type"))
                ->where("season.status", "=", 1)
                ->Where("season.name", "like", "%".$search."%")
                ->orWhere("season.content", "like", "%".$search."%")
                ->orWhere("season.variables", "like", "%".$search."%")
                ->orderBy("title", "asc")
                ->paginate(5);

【问题讨论】:

  • 我不了解 laravel,但你不能只做$result = $nresult->merge($sresult); 看到这个问题:stackoverflow.com/questions/41756404/…
  • 它适用于合并,但分页存在问题。我确实将它替换为 ->get(); 仍然希望它有分页
  • 现在有这个问题Method Illuminate\Support\Collection::paginate does not exist.
  • 看来你想同时问两个问题。你问的是合并数据。

标签: php database laravel-5 pagination


【解决方案1】:

您可以使用union 运算符将两个选择语句组合成一个语句。然后你可以申请一个全局的orderBypaginate

$news = DB::table("news")
    -> ...
    ->orWhere(...);

$result = DB::table("season")
    -> ...
    ->orWhere(...)
    ->union($news)
    ->orderBy("title")
    ->paginate(10);

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多