【问题标题】:How to combine multiple Eloquent collections in Laravel如何在 Laravel 中合并多个 Eloquent 集合
【发布时间】:2016-07-22 10:54:32
【问题描述】:

我想将各种模型合并为一个(用于输出到 DataTables 实例中)。

到目前为止,我已经这样做了(实际上大约有 15 个模型,我这里只展示两个):

$all_records = new Collection;

$care_plan_updates = \App\CarePlanUpdate::where('resident_id', $resident->id)->where('closed','0')->get();
if($care_plan_updates) $all_records = $all_records->merge($care_plan_updates);  

$medication_errors = \App\MedicationError::where('resident_id', $resident->id)->where('closed','0')->get();
if($medication_errors) $all_records = $all_records->merge($medication_errors);

return Datatables::of($all_records)

在第一印象中,这似乎做得很好。但是,我注意到 merge 方法合并了共享 ID 值的记录。例如,ID 为 12 的 CarePlanUpdate 被 ID 为 12 的 MedicationError 记录覆盖。

我尝试过“忘记” ID 列,但这似乎没有任何效果:

if($care_plan_updates) $all_records = $all_records->merge($care_plan_updates->forget('id'));

理想情况下,我想要一种简单地组合两个集合而不合并具有重复值的行的方法。我是 Eloquent 的新手 - 所以任何关于我哪里出错的指导都将非常感激!

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    我找到了解决办法。我不确定这是实现我目标的最优雅的方式,但它确实有效:

    我决定循环遍历每个单独的集合并使用push 将每条记录添加到我的主集合中,而不是使用merge 集合方法。像这样:

    $all_records = new Collection;
    
    $care_plan_updates = \App\CarePlanUpdate::where('resident_id', $resident->id)->where('closed','0')->get();  
    foreach($care_plan_updates as $care_plan_update) {
        $all_records->push($care_plan_update);
    }   
    
    $risk_assessment_updates = \App\RiskAssessmentUpdate::where('resident_id', $resident->id)->where('closed','0')->get();
    foreach($risk_assessment_updates as $risk_assessment_update) {
        $all_records->push($risk_assessment_update);
    } 
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 2017-04-12
      • 2019-10-13
      • 2018-11-11
      • 2015-11-29
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2021-02-13
      相关资源
      最近更新 更多