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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?