【发布时间】:2016-06-05 21:05:04
【问题描述】:
使用 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' 我不想从$days 合并'2016-02-24'。我该怎么做?
【问题讨论】:
-
它们不是碳对象,只是字符串。合并可能是下面的答案。如果你想做一些过滤,请使用集合的过滤方法
-
如果没有
collections,你的头会很痛。 -
@MikeMiller 我的意思是它们被转换为 Carbon 实例。见:laravel.com/docs/5.1/eloquent-mutators#introduction
-
那么这些系列是什么样子的?
-
添加了一个可能解决您的问题的答案,但我不知道为什么合并只会合并最后一项。
标签: php laravel laravel-5 laravel-collection