【问题标题】:Laravel 5: Eloquent & form model for business hoursLaravel 5:工作时间的 Eloquent & form 模型
【发布时间】:2015-12-09 12:34:57
【问题描述】:

我正在尝试为我的用户实施营业时间。所以我有基本的用户表和 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() / 输入,laravel 将在更新特定用户的营业时间时自动使用提供的值填充必要的输入?

我在考虑这个输入组织:

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

请注意,用户可以根据需要设置每天多次(添加新行列)。

感谢您的想法

【问题讨论】:

  • 我自己还没有遇到过这种情况,但是我发现this other stacklink which night给出了解决方案。这里的解决方案不使用 Form::model,而是使用 Form::open。 stackoverflow.com/questions/20684932/…
  • 我们遇到了类似的问题,不好的是 laravel 不会自动匹配数组输入名称。我认为您必须遍历所有 business_hours ...问题是 FormBuilder 中的 transformKey() 方法。这会将可以识别数组索引/键的每个字符转换为下划线或其他符号......唯一的方法是将模型转换为数组并将数组用作模型,然后它可以匹配诸如“example [0 ]" 到数组元素 [example => [0 => 'xxx']]]

标签: php sql forms laravel eloquent


【解决方案1】:

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

{!! 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'
    ]
}

【讨论】:

    猜你喜欢
    • 2015-03-12
    • 2017-09-13
    • 2017-09-02
    • 2016-02-06
    • 2016-08-17
    • 2019-06-02
    • 2015-08-16
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多