5

使用 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我该怎么做呢?

4

3 回答 3

5

使用merge

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

文档

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

于 2016-02-23T20:33:55.250 回答
2

我不确定为什么$merged = $timesheets->merge($days);只合并最后一项。也许其他人可以对此有所了解。

但在有更好的解决方案之前,你可以这样做——

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

希望这可以帮助。

于 2016-02-24T09:40:43.527 回答
1

好吧,试试这个。逻辑应该几乎可以解决,但 obv 无权访问您的 Timesheet 类..

$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);
于 2016-02-24T17:59:27.090 回答