php - 合并两个 Laravel 集合

标签 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 集合中。例如如果 $timesheets 已经包含 '2016-02-24'想要合并 '2016-02-24' 来自 $days。我该怎么做?

最佳答案

使用合并:

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

Documentation

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

关于php - 合并两个 Laravel 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587509/

相关文章:

php - CakePHP - 使用元素将变量从 Controller 传递到布局

php - laravel 存储过程错误

javascript - 如何修改 laravel 中间件以使用 firebase 身份验证

laravel - 使用 whereHas 或其他类型的查询重构 3 个父子类别关系查询?

php - Laravel 中的闭包是什么?

php - codeigniter 路由任何或 num 不工作

php - 从 php.ini 包含的路径自动加载命名空间类

php - 如何确保在 MySQL 中同时对 2 个表进行相等更新

php - laravel 获取数据没有得到想要的结果

php - Laravel/Lumen 中两列之间的 SQL