Laravel 查询多个模型并合并结果

Mat*_*rce 1 laravel laravel-5

在我的应用程序中,我返回一个包含 Posts 模型中所有记录的视图。我现在有另一个模型,我想返回其结果,并且在同一视图中我想将 Post 模型和这个新模型的查询结果结合起来。合并后,我想按“created_at”日期对结果进行排序。

我一直在尝试在查询生成器上使用 Union 方法,但收到错误“所使用的 SELECT 语句具有不同数量的列...”。创建一个包含这些模型以及我将来创建的其他模型的所有结果的总体表可能会更容易。

控制器:

$connectionsPosts = Post::where(function($query) {
        return $query->where('user_id', Auth::user()->id)
            ->orWhereIn('user_id', Auth::user()->following()->lists('connection_id'));
    });

$request = DB::table('request')->union($connectionsPosts)->get();

return view('main.discover.connections')
    ->with([
        'connectionsPosts' => $request,
    ]);
Run Code Online (Sandbox Code Playgroud)

更新:

看法:

@if ($connectionsPosts->count())
    @foreach ($connectionsPosts as $Posts)
        // Provide markup to loop through results
    @endforeach
@endif
Run Code Online (Sandbox Code Playgroud)

我正在努力实现这样的目标

@foreach ($allResults as $results)
    // Some markup that includes both connectionsPosts and request based on the "created_at" date
@endforeach
Run Code Online (Sandbox Code Playgroud)

cra*_*bly 5

为此,请使用 Laravel Collections。

在您的示例中,您的第一个结果存储在$request. 假设您还有一些其他结果存储在$otherRequest.

首先使用该merge方法合并两个结果:

$mergedRequest = $request->merge($otherRequest);
Run Code Online (Sandbox Code Playgroud)

然后使用sortBy方法:

$sorted = $mergedRequest->sortBy('created_at');
Run Code Online (Sandbox Code Playgroud)