合并两个Laravel系列

时间:2016-02-23 20:29:05

标签: php laravel laravel-5 laravel-collection

我的头脑因使用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集合中存在的任何重复项。 E. g。如果$timesheets已包含'2016-02-24' 想要从'2016-02-24'合并$days。我该怎么做?

3 个答案:

答案 0 :(得分:5)

使用merge

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

Documentation

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

答案 1 :(得分:2)

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

但是,除非有更好的解决方案,否则你可以这样做 -

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

希望这有帮助。

答案 2 :(得分: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);