【问题标题】:Laravel Query Multiple Models and Combine ResultsLaravel 查询多个模型并合并结果
【发布时间】:2016-09-28 22:17:43
【问题描述】:

在我的应用程序中,我返回一个视图,其中包含 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,
    ]);

更新:

查看:

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

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

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

【问题讨论】:

    标签: laravel laravel-5.2


    【解决方案1】:

    这不关我的事,但你为什么不这样做:

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

    不过试试这个

    $connectionsPosts = Post::where(function($query) {
            return $query->where('user_id', Auth::user()->id)
                ->orWhereIn('user_id', Auth::user()->following()->lists('connection_id'));
        })->get();
    
    $request = DB::table('request')->get();
    
    $connectionPostsAndRequests = $request->merge($connectionsPosts);
    $connectionPostsAndRequests->sortBy('created_at');
    
    return view('main.discover.connections')
        ->with([
            'connectionsPosts' => $connectionPostsAndRequests,
        ]);
    

    不知道行不行

    【讨论】:

    • 绝对是你的事,因为我正在寻求你的帮助:)。我没有这样做,因为我希望根据它们的“created_at”值将两个表的结果混合在一起。如果我按照您的建议进行操作,我相信我将获得一部分 $connectionsPosts 结果和另一部分 $request 结果。不过我可能是错的。
    • 部分?您将在视图中获得 2 个变量 connectionsPostsrequest。发生错误是因为您的 2 个查询具有不同的列数。尝试直接设置列。
    • 我认为我描述得不好。请查看我更新的问题,其中包含我如何遍历视图中的结果以及我想要实现的目标。谢谢!
    • 忘记在合并的集合上调用->sortBy('created_at')
    【解决方案2】:

    为此使用 Laravel 集合。

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

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

    $mergedRequest = $request->merge($otherRequest);
    

    然后使用sortBy方法:

    $sorted = $mergedRequest->sortBy('created_at');
    

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多