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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题