【发布时间】:2021-07-21 14:21:48
【问题描述】:
2 种模型:FMType 和 Profile。 FMPType 有许多 Profile 记录(一对多关系)。
class FMPType extends Model
{
public function profiles()
{
return $this->hasMany(Profile::class, 'fmptype_id');
}
}
和
class Profile extends Model
{
public function fmptype() {
return $this->belongsTo(FMPType::class);
}
}
我需要将一些 FMPType 复制到另一个,包括相关的 Profiles:
public function copy(Request $request, int $fmptype)
{
$source = FMPType::findOrFail($fmptype);
// Double type
$target = $source->replicate();
$target->name = $source->name . ' (Copy)';
$target->save();
// Double profiles
foreach ($source->profiles as $profile) {
$targetProfile = $profile->replicate();
// Associate new Profile with new FMPType
// Attempt 1: add - nothing happened, works silent, link remains as in source
$target->profiles->add($targetProfile);
// Attempt 2: associate - error, no such method
$target->profiles()->associate($targetProfile);
$targetProfile->save();
}
return somewhere;
}
在这里,我无法使用 Eloquent 方法将子配置文件与父 FMPType 关联。
唯一的直接分配有效:$targetProfile->fmptype_id = $target->id,但从 Eloquent 的角度猜想这是错误的方式。
应该怎样做这样的关联?
更新 - 工作原理:
public function copy(Request $request, int $fmptype)
{
$source = FMPType::findOrFail($fmptype);
// Double type
$target = $source->replicate();
$target->name = $source->name . ' (Copy)';
$target->save();
// Double profiles
foreach ($source->profiles as $profile) {
$targetProfile = $profile->replicate();
// Associate new Profile with new FMPType
// Save both relation and $targetProfile
$target->profiles()->save($targetProfile);
// This save() is not required anymore
// $targetProfile->save();
}
return somewhere;
}
【问题讨论】:
标签: laravel eloquent relationship