dtgu21994537 2016-07-22 10:54
浏览 328
已采纳

如何在Laravel中组合多个Eloquent集合

I have various models that I would like to combine into one (for output into a DataTables instance).

So far I have done this (in reality there are about 15 models, I'm just showing two here):

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

On first impressions this seemed to have done the trick well. However, I've noticed that the merge method combines records that share an ID value. So for example, the CarePlanUpdate with an ID of 12 is overridden by the MedicationError record with the ID of 12.

I have tried 'forgetting' the ID column but this doesn't seem to have any effect:

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

Ideally, I'd like a method that simply combines two collections without merging rows with duplicate values. I'm new to Eloquent - so any guidance on where I'm going wrong would be really appreciated!

  • 写回答

1条回答 默认 最新

  • dongwenxiu5200 2016-07-22 11:24
    关注

    I have found a solution. I'm not sure it's the most elegant way of achieving my goal though but it does the trick:

    Rather than using the merge collection method I decided to loop through each individual collection and use push to add each record to my master collection. Like so:

    $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);
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?