我因为使用 Laravel 集合而头疼。我有两个收藏:
$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 ...
我有第二个集合,给出了给定月份的所有天数。
\Illuminate\Support\Collection
($days
)
#attributes: array:1 [▼
"date" => "2016-02-01 00:00:00"
]
// ... and the rest of the month.
我想将 $days
集合与 $timesheet
集合合并,保留 $timesheet
集合的值并删除所有重复项在 $days
集合中。例如如果 $timesheets
已经包含 '2016-02-24'
我不想要合并 '2016-02-24'
来自 $days
。我该怎么做?
最佳答案
使用合并
:
$collection1 = Model1::all();
$collection2 = Model2::all();
$mergedCollection = $collection1->merge($collection2);
文档讨论了如何将它与数组一起使用,但查看 method signature它将采取混合论据。在 Laravel 4 项目的本地安装上测试它对我有用。
关于php - 合并两个 Laravel 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587509/