【问题标题】:Create method not adding multiple results创建方法不添加多个结果
【发布时间】:2017-05-03 20:53:17
【问题描述】:

我有一个刀片模板,用户可以在其中通过动态下拉菜单添加多个选项option[]

如果我输出数组,它会显示(正确):

array:3 [▼
  0 => "sdfsdfsdf"
  1 => "sdfsdfsdflj"
  2 => ""
]

上述输入与action_points 表中的point 列相关。

上表的模型:

 protected $fillable = [
        'audit_score_id', 'point', 'actioned',
    ];

    public function audit()
    {
        return $this->belongsTo(AuditScore::class);
    }

该表具有belongsTo 关系,因此每一行都有一个audit_score_id 列。

除了存储point信息,我还想存储audit_score_id

当我使用下面的函数时,表中只保存了 1 个空行:

$actions = $request->get('option');

$item = array();
foreach ($actions as $action) {
    $item = ([
        'point' => $action,
   ]);
}

$audit = AuditScore::find($id);
$audit->actionPoints()->create($item);

保存的行:

id  audit_score_id  point   actioned
5         32                    0

任何帮助将不胜感激。

非常感谢。

【问题讨论】:

    标签: laravel foreach laravel-5.4 mass-assignment


    【解决方案1】:

    您有一个错误,您的代码实际上只有一项,即最后一个$action。更改填充数组的方式。

    $actions = $request->get('option');
    
    $item = array();
    foreach ($actions as $action) {
        // this notation is for pushing items to the array
        $item[] = [
            'point' => $action,
       ];
    }
    
    $audit = AuditScore::find($id);
    $audit->actionPoints()->create($item);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 2015-04-05
      • 1970-01-01
      相关资源
      最近更新 更多