我有两个表来处理动物的父母,在数据透视表中我存储子动物和父母动物的“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 关注
- 75 浏览
添加回答
举报
0/150
提交
取消