合并两个 Laravel collections

Merging two Laravel collections

与 Laravel collection 一起工作让我头疼。我有两个 collections:

    $dt = Carbon::now();
    $days = new Collection([]);

    /**
     * Create a calender month
     */
    for ($day = 1; $day <= $dt->daysInMonth; $day++) {
        $date = Carbon::create($dt->year, $dt->month, $day)->toDateString();
        $days->push(new Timesheet([
            'date' => $date,
        ]));
    }

    /**
     * Get all timesheets for user
     */
    $timesheets = Timesheet::where('user_id', $this->user->id)
        ->get();

\Illuminate\Database\Eloquent\Collection ($timesheets)

#attributes: array:5 [▼
    "id" => "1"
    "user_id" => "1"
    "date" => "2016-02-22 22:05:01"
    "created_at" => "2016-02-22 22:05:01"
    "updated_at" => "2016-02-22 22:05:01"
  ]
  // ... one or more ...

我有第二个 collection 给定月份的所有天数。

\Illuminate\Support\Collection ($days)

#attributes: array:1 [▼
    "date" => "2016-02-01 00:00:00"
]
// ... and the rest of the month.

我想将 $days collection 与 $timesheet collection 合并,保留 $timesheet collection 的值并删除任何$days collection 中存在重复项。例如如果 $timesheets 已经包含 '2016-02-24' 不想 $days 合并 '2016-02-24'。我该怎么做?

使用merge:

$collection1 = Model1::all();
$collection2 = Model2::all();
$mergedCollection = $collection1->merge($collection2);

Documentation

文档讨论了将它与数组一起使用,但查看 method signature 它将采用混合参数。在 Laravel 4 项目的本地安装上测试它对我有用。

我不确定为什么 $merged = $timesheets->merge($days); 只合并最后一项。也许其他人可以阐明它。

但在没有更好的解决方案之前,您可以这样做 -

$merged = array_merge($timesheets->toArray(), $days->toArray());

希望对您有所帮助。

好的,开始吧。逻辑应该很清楚,但 obv 无法访问您的时间表 class..

$days = new Collection([]);

//basically the same structure i think
$timesheets = new Collection([new Collection(['date'=>'2016-02-23','created_at'=>'2016-02-23 14:12:34']),new Collection(['date'=>'2016-02-28','created_at'=>'2016-02-23 14:15:36'])]);

$dt = Carbon::now();

for ($day = 1; $day <= $dt->daysInMonth; $day++) {

    $date = Carbon::create($dt->year, $dt->month, $day)->format('Y-m-d');

    //filter your timesheets and see if there is one for this day
    $timesheet = $timesheets->filter(function($timesheet) use($date){return $timesheet->get('date')==$date;});

    if(!$timesheet->isEmpty()){
        //if there is a timesheet for today then add it to your $days collection
        $days->push($timesheet);
    }else{
        //otherwise just stick in the date
        $days->push(new Collection([
            'date' => $date,
        ]));
   }
}

//voila!
dd($days);