Combining two different with no relationship DB ta

2019-07-18 19:28发布

问题:

I have two tables in my database that are not related, and I need those to be merge so I can put it on my search view but I don't have any idea, if it is possible or not.

Here is my code. The news and season tables are not related but they have similar columns which I am trying to put in one object for easy pagination. Is it possible?

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

回答1:

You can combine two select statements into one statement with the union operator. Then you can apply a global orderBy and paginate:

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

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