如何在实例化对象上保存关联

How to save associations on an instantiated object

如何在保存“parent”之前关联其他关联?我有一辆有许多其他零件的汽车:

问题是,如果座椅或脚垫有任何缺陷,则无法制造汽车:

$car = new Car(...);

// Many mats
$mats = [new Mat(..), new Mat(..)];

// One mirror
$mirror = new Mirror(..);

// I need to put them all together.
// This does not work
$car->saveMany([$mats, $mirror, $mats]);

// Does not work
$car->mats()->saveMany($mats);
$car->associate($mirror);

// Car should not be saved if either any of its associations have an error.
$car->save();

The docs 在实例化一个新对象然后保存其关联时未提及此示例:HasMany、HasOne、BelongsTo 等

我看过这些但无法理解:

如何通过调用“save()”来“关联”“汽车”关联?

我建议您查看 laravel 的验证功能。 (https://laravel.com/docs/8.x/validation)

您可以进行嵌套验证,例如,如果您想验证汽车的座位,您可以制定如下规则:

public function store(Request $request)
{
    $validated = $this->validate($request, [
        'name' => 'required|string',
        'model' => 'required|exists:car_models,name',

        'seats' => 'required|array',
        'seats.*.color' => 'required',
        'seats.*.width' => 'numeric',
        'seats.*.fabric' => 'required|string',
    ]);

    // create the car with all relation data

    return $car;
}

验证可以如上所示完成,或通过表单请求验证 (https://laravel.com/docs/8.x/validation#form-request-validation)。

这样,您可以确保用户输入有效并且在创建任何模型之前都能正常工作。之后你应该创建汽车并添加所有关系。但是,我建议您改为使用 eloquent 关系,这样您就可以编写类似

的内容
// Create relation model with array of data
$car->seats()->create($seatData);

// Create relation models with collection of data
$car->seats()->createMany($seatsDataCollection);