Laravel 5:雄辩营业时间的表单模型


Laravel 5: Eloquent & form model for business hours

我正试图为我的用户实现营业时间。因此,我有基本用户表和user_business_hours表,如下所示:

| id | user_id | weekDay | start_time | end_time | created_at | updated_at |
|---:|---------|--------:|------------|----------|------------|------------|
| 1  | 10      | 1       | 10:00:00   | 12:00:00 | ...        | ...        |
| 2  | 10      | 1       | 13:30:00   | 18:00:00 | ...        | ...        |

现在的问题是:如何查询此模型并设置Form::model()/input,以便在为特定用户更新营业时间的同时,自动使用提供的值填充必要的输入?

我在考虑这个输入组织:

| ...     | Work From | Work From | add new row |
|---------|-----------|-----------| ----------- |
| Monday  | 10:00:00  | 12:00:00  | +           |
| Monday  | 13:30:00  | 18:00:00  | +           |
| Tuesday | <input>   | <input>   | +           |

请注意,用户可以每天设置尽可能多的次数(添加新的行列)。

谢谢你的想法

解决方案是将模型转换为数组:

{!! Form::model($model->toArray(), []) !!}
    {!! Form::text('business_hour[0][from]', null, []) !!}
    {!! Form::text('business_hour[0][to]', null, []) !!}
    {!! Form::text('business_hour[1][from]', null, []) !!}
    {!! Form::text('business_hour[2][to]', null, []) !!}
{!! Form::close() !!}

根据你的数组结构——在后台,array_get()助手正在运行,字段名通过transformKey()方法进行转换。

protected function transformKey($key)
{
    return str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $key);
}

如果您将模型作为对象交付,那么其中的所有内容也必须是对象,因此不可能使用以下内容:

{
    'key' => [
        'hallo' => 'welt'
    ]
}