我正在尝试使用一种形式来保存两个表。我的表格收集设备“签入/签出”的数据并收集该签入/签出的图片。收集到的字符串数据存储在Traffic表中,而图像数据将存储在Details表中。Traffic签入/签出的条目可以有很多Details。属于Details特定Traffic条目。我的设置方式不断出现BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::detail()错误。这是我的交通控制器: auth()->user()->traffic()->create([ 'branch' => $data['branch'], 'io' => $data['io'], 'make' => $data['make'], 'model' => $data['model'], 'sn' => $data['sn'], 'customer' => $data['customer'], ]); if ($upload['isSuccess']) { foreach($upload['files'] as $key=>$item) { $upload['files'][$key] = array( auth()->user()->traffic()->detail()->create([ 'extension' => $upload['files'][$key]['extension'], 'format' => $upload['files'][$key]['format'], 'file' => 'storage/' . $uploadDir . $upload['files'][$key]['name'], 'name' => $upload['files'][$key]['name'], 'size' => $upload['files'][$key]['size'], 'size2' => $upload['files'][$key]['size2'], 'title' => $upload['files'][$key]['title'], 'type' => $upload['files'][$key]['type'], 'url' => 'http://localhost:8000/storage/' . $uploadDir . $upload['files'][$key]['name'], ])); } } else { foreach($upload['warnings'] as $error) { // echo $error . '<br>'; } }我的流量模型 public function user() { return $this->belongsTo(User::class); } public function detail() { return $this->hasMany(Detail::class); }我的详细模型 public function traffic() { return $this->belongsTo(Traffic::class); } public function user() { return $this->belongsTo(User::class); }
1 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
由于用户可以拥有许多流量资源,因此您无需指定要将详细信息资源添加到哪个流量资源。您应该在创建新的流量资源时将其分配给一个变量:
$traffic = auth()->user()->traffic()->create([
'branch' => $data['branch'],
'io' => $data['io'],
'make' => $data['make'],
'model' => $data['model'],
'sn' => $data['sn'],
'customer' => $data['customer'],
]);
当您创建新的详细资源时,(might want to change the relationship from detail to details since it suggests many like your hasMany relationship where detail suggets hasOne)您可以调用:
$traffic->detail()->create([
...
]);
我还注意到您正在循环遍历数组来创建新的详细资源。实际上有一个createMany()
指针函数可以帮助简化该过程。
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消