我有兩個表來處理動物的父母,在數據透視表中我存儲子動物和父母動物的“id”,在另一個表中我有一個性別字段來定義它是母親還是父親。問題是在更新這些數據時,因為是多對多的關系,我只能打電話給所有的父母,我想要的是一一更新,將他們與性別進行比較。在我的“Ganado”模型中,我定義了兩個函數來查看父母并分配它們:public function padres(){ return $this->belongsToMany('App\Ganado', 'hijos_padres', 'id_hijo', 'id_padre');}public function hijos(){ return $this->belongsToMany('App\Ganado', 'hijos_padres', 'id_padre', 'id_hijo');}public function asignarPadre($id_padre){ $this->padres()->sync($id_padre, false);}在我的控制器中,我像這樣更新數據:public function update(Request $request, $id){ $bovino = Ganado::findOrFail($id); $bovino->codigo_ganado = $request->get('codbovino'); $bovino->nombre = request('nombre'); $bovino->lote_ingreso = request('loteIn'); $bovino->lote_actual = request('loteAct'); $bovino->ganaderia = $request->get('ganaderia'); $bovino->etapa = $request->get('etapa'); $bovino->genero = $request->get('genero'); $bovino->id_raza = $request->get('raza'); $bovino->fecha = Carbon::createFromFormat('d/m/Y', $request->input('fechaNac'))->format('Y-m-d'); if ($request->hasFile('imagen')) { $file = $request->imagen; $file->move(public_path() . '/images', $file->getClientOriginalName()); $bovino->imagen = $file->getClientOriginalName(); } //This is how im trying to update a parent $id_padre = $bovino->padres()->pluck('id_padre')->toArray(); $bovino->padres()->updateExistingPivot($id_padre, ['id_padre' => $request->get('padre')]); $bovino->update(); return redirect('/ganado/engorde');}最后,我想更新父母雙方(父親和母親),并且我有 2 個“選擇”,其中顯示了所有這些。
1 回答

千巷貓影
TA貢獻1829條經驗 獲得超7個贊
將其與性別進行一一更新的代碼:
// $padres is a collection containing both parents
$padres = $bovino->padres()->get();
// foreach loop to differentiate the mother and father
foreach($padres as $padre){
if($padre->genero === GENERO_MUJER){
//mother
} else {
//father
}
}
- 1 回答
- 0 關注
- 112 瀏覽
添加回答
舉報
0/150
提交
取消