【发布时间】:2019-05-06 08:29:25
【问题描述】:
我是 Laravel 的新手,我遇到了这个问题: 我有 2 个表,platos 和成分,它们具有多对多关系,为此我使用了第三个表,称为成分_platos。
为了保存多对多的关系,我尝试了以下方法:
$platos->ingredientes()->attach($input['ingredientes']);
但它给出了以下错误:
SQLSTATE[23000]:完整性约束违规:1062 键“PRIMARY”的重复条目“151-3”(SQL:插入ingredientes_platos(platos_id,ingredientes_id,norma_bruta)值(151, 3, ))
看了一下文档,我可以用同步而不是附加来解决,但这并不能解决我的问题,因为除了保存关系的 id 之外,我还需要在数据透视表中保存其他属性。
重要的是要注意,如果我尝试将这些数据保存在 components_platos 以外的表中,我不会遇到这个问题,并且无论我使用哪种方法,数据都会正确保存。
感谢您的关注,希望您能帮助我。
这些是三个表的模型:
表柏拉图:
public $table = 'platos';
protected $dates = ['deleted_at'];
public $fillable = [
'Grupo',
'Nombre',
'Procedimiento',
'Cantidad',
'Unidad',
'Precio'
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'Grupo' => 'integer',
'Nombre' => 'string',
'Procedimiento' => 'string',
'Cantidad' => 'integer',
'Unidad' => 'integer',
'Precio' => 'double'
];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
'Grupo' => 'required',
'Nombre' => 'required'
];
public function ingredientes()
{
return $this->belongsToMany(Ingredientes::class);
}
public function grupo_platos()
{
return $this->hasOne('App\Models\Grupo_Platos', 'id', 'Grupo');
}
}
餐桌配料:
public $table = 'ingredientes';
protected $dates = ['deleted_at'];
public $fillable = [
'Grupo',
'Nombre',
'Descripcion',
'Kcal',
'Proteinas',
'Grasas',
'Unidad',
'Precio'
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'Grupo' => 'integer',
'Nombre' => 'string',
'Descripcion' => 'string',
'Kcal' => 'double',
'Proteinas' => 'double',
'Grasas' => 'double',
'Unidad' => 'integer',
'Precio' => 'double'
];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
'Nombre' => 'required'
];
public function platos()
{
return $this->belongsToMany(Platos::class);
}
}
餐桌配料_柏拉图:
public $table = 'ingredientes_platos';
public $fillable = [
'platos_id',
'ingredientes_id',
'norma_bruta',
'norma_neta',
'unidad_id'
];
public $timestamps = false;
}
Platos 控制器:
public function store(CreatePlatosRequest $request)
{
$input = $request->all();
$platos = $this->platosRepository->create($input);
$id = $platos->id;
$ingredientes = $input['ingredientes'];
$norma_b = $input['norma_b'];
$t = sizeof($ingredientes);
$i=0;
for ($i = 0; $i < $t; $i++) {
$pivot = new Ingredientes_Platos;
$pivot->platos_id = $platos['id'];
$pivot->ingredientes_id = $ingredientes[$i];
$pivot->norma_bruta = $norma_b[$i];
$pivot->save();
}
Flash::success('Plato agregado correctamente.');
return redirect(route('platos.index'));
}
【问题讨论】:
标签: laravel many-to-many relationship