我在Home
模型和Phones
模型之间存在一对多的关系
public function phones() {
return $this -> hasMany(Phone::class);
}
和在手机型号中:
public function homes() {
return $this -> belongsTo(Home::class);
}
现在在我的控制器中,当我插入Home
时,我想使用它来向Phone
表中添加与{{1相同的id
}}。这是我现在插入的方式:
Home
现在,我想知道如何在电话表和房地产中插入public function store(StoreHome $request) {
$validated = $request -> all();
if (!$validated) {
return $this -> sendError('Validation Error.', $validated -> errors());
}
$home = Home::create($validated);
return new HomeResource($home);
}
和许多Home
。
答案 0 :(得分:1)
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
有关详细信息,请阅读文档https://laravel.com/docs/5.8/eloquent-relationships#inserting-and-updating-related-models
更新示例:
假设您使用多个输入字段进行数字输入。
<input name="numbers[]">
<input name="numbers[]">
$phones = [];
$numbers = $request->input('numbers');
foreach($numbers as $number){
$phones[] = [
'number' => $number
];
}
$home->phones()->createMany($phones);
答案 1 :(得分:0)
自创建家庭以来,可以在关系上使用save
或saveMany
:
$home->phones()->saveMany([
new App\Phone(['phone' => '039049230490']),
new App\Phone(['phone' => '039049223132']),
]);
您可以在这里找到所有文档:https://laravel.com/docs/5.8/eloquent-relationships#the-save-method