【问题标题】:Laravel Nova - Create many objects with a single form submissionLaravel Nova - 使用单个表单提交创建许多对象
【发布时间】:2020-09-29 20:43:28
【问题描述】:

我的 Laravel Nova 中有一个部分,我可以从中创建课程时间表。在前端,我的老师可以通过定义 repeat_till 和 repeat_frequency 字段轻松地从一个表单创建多个类。我怎样才能在 Laravel Nova 中获得相同的结果?

我自己的控制器有如下代码:

if($data['repeat'] && $data['repeat_till']) {
    $next_date = Carbon::parse($data['date']);
    $end_date = Carbon::parse($data['repeat_till']);
                
    while($next_date <= $end_date) {
        $dates[] = $next_date->format('Y-m-d');   
        $next_date = $next_date->addDays($data['repeat']);
    }
 } else {
    $dates[] = $data['date'];
 }

...

$parent = null;

foreach($dates as $date) {
    $schedule = Schedule::create([
        ...
        'date' => $date,
        'parent_id' => ($parent ? $parent->id : null),
        ...
    ]);

    if(!$parent) {
        $parent = $schedule;
    }
}

我已经研究过为此使用观察者的可能性,到目前为止,这似乎是唯一可行的选择。但是,为此我需要访问 repeat(repeat_frequency) 和 repeat_till 值,它们不是 Schedule 模型的一部分。如何在 created 方法中访问这些值?

【问题讨论】:

    标签: laravel laravel-nova


    【解决方案1】:

    您可以通过覆盖模型中的保存功能来做到这一点 公共函数保存(数组 $options = 数组())

    并且由于您无法访问观察者内部的 repeat_frequency 和 repeat_till 值,我猜这些不是数据库字段..所以我建议在保存模型之前取消设置这些变量.. EX:

    public function save(array $options = array())
    {
    
        if($this->exists == false)
        {
            //means you're creating a model
            
    
            //this is where you write your code
            foreach($dates as $date) {
            $schedule = Schedule::create([
                ...
                'date' => $date,
                'parent_id' => ($parent ? $parent->id : null),
                ...
                ]);
    
            }
    
    
        }
        else
        {
            //updating a model
        }
    
        //you need to comment this since you're creating the schedules in a different way
        //parent::save($options);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2019-03-08
      • 2016-10-26
      • 2023-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2018-11-12
      相关资源
      最近更新 更多