我正在嘗試使用一種形式來保存兩個表。我的表格收集設備“簽入/簽出”的數據并收集該簽入/簽出的圖片。收集到的字符串數據存儲在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 關注
- 105 瀏覽
添加回答
舉報
0/150
提交
取消