5

Laravel コレクションの操作で頭が痛くなります。私は2つのコレクションを持っています:

    $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 ...

特定の月のすべての日を提供する 2 番目のコレクションがあります。

\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 に答える
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 に答える