提前1个月添加记录

时间:2018-04-23 08:46:18

标签: php laravel

我有这段代码:

$tasks = new Task();
$tasks->text = 'Velo';
$tasks->role_id = 1;
$tasks->progress = 0.0;
$tasks->duration = 1;
$tasks->start_date = Carbon::now()->addMonth();
$tasks->parent = 0;
$tasks->type = "project";
$tasks->color = '#ccc';

$tasks->save();

$tasks = new Task();
$tasks->text = 'Auto';
$tasks->role_id = 1;
$tasks->progress = 0.0;
$tasks->duration = 1;
$tasks->start_date = Carbon::now()->addMonth();
$tasks->parent = 0;
$tasks->type = "project";
$tasks->color = '#ccc';

$tasks->save();

$tasks = new Task();
$tasks->text = 'Moto';
$tasks->role_id = 1;
$tasks->progress = 0.0;
$tasks->duration = 1;
$tasks->start_date = Carbon::now()->addMonth();
$tasks->parent = 0;
$tasks->type = "project";
$tasks->color = '#ccc';

$tasks->save();

如何提前一个月添加这些记录?我需要循环吗?但约会?我如何添加记录?我本月需要每天都有他们的记录。

3 个答案:

答案 0 :(得分:0)

对于这种类型的场景,你可以laravel mutators。

这是一个例子

 public function setStartDateAttribute($value)
    {
        $this->attributes['start_date'] = Carbon::now()->addMonth();
    } 

将上述功能放入您的模型中,然后您不需要为每次插入设置日期。

了解更多信息 https://laravel.com/docs/5.6/eloquent-mutators

希望这有帮助。

答案 1 :(得分:0)

如果您想添加多个任务,请始终使用循环。希望以下代码可以帮助你..

  V1 V2
1  A  a
2  B  a
3  C  a
6  A  b

答案 2 :(得分:0)

是的,你需要一个循环和一个日期周期来循环

$from = \Carbon\Carbon::today();
$to = $from->copy()->addMonth();

$period = new \DatePeriod($from, new \DateInterval('P1D'), $to);

foreach ($period as $date) {
    $tasks = new Task();
    $tasks->text = 'Velo';
    $tasks->role_id = 1;
    $tasks->progress = 0.0;
    $tasks->duration = 1;
    $tasks->start_date = $date;
    $tasks->parent = 0;
    $tasks->type = "project";
    $tasks->color = '#ccc';

    $tasks->save();

    $tasks = new Task();
    $tasks->text = 'Auto';
    $tasks->role_id = 1;
    $tasks->progress = 0.0;
    $tasks->duration = 1;
    $tasks->start_date = $date;
    $tasks->parent = 0;
    $tasks->type = "project";
    $tasks->color = '#ccc';

    $tasks->save();

    $tasks = new Task();
    $tasks->text = 'Moto';
    $tasks->role_id = 1;
    $tasks->progress = 0.0;
    $tasks->duration = 1;
    $tasks->start_date = $date;
    $tasks->parent = 0;
    $tasks->type = "project";
    $tasks->color = '#ccc';

    $tasks->save();
}

您还可以简化循环

$tasks = ['Velo', 'Auto', 'Moto'];

foreach ($period as $date) {
    foreach ($tasks as $task) {
        $task = new Task();
        $task->text = $task;
        $task->role_id = 1;
        $task->progress = 0.0;
        $task->duration = 1;
        $task->start_date = $date;
        $task->parent = 0;
        $task->type = "project";
        $task->color = '#ccc';
        $task->save();
    }
}