[英]Eloquent - inserting related models
In this question the accepted answer to saving related models was:在这个问题中,保存相关模型的公认答案是:
public function store(Request $request)
{
$player->name = $request->input('name');
$player->lastname = $request->input('lastname');
$player->stats = [
'position' => $request->input('stats.position'),
'profile' => $request->input('stats.profile'),
];
$player->save();
return response()->json($player);
}
Whenever I try this I get an error:每当我尝试这个时,我都会收到一个错误:
Column not found: 1054 Unknown column 'stats' in 'field list'未找到列:“字段列表”中的 1054 列“统计信息”未知
If I add stats to the guarded collection, it of course never comes in.如果我将统计信息添加到受保护的集合中,它当然永远不会出现。
On my player object I have this:在我的播放器对象上,我有这个:
public function stats(): HasMany
{
return $this->hasMany(Stat::class);
}
So how can I have my stats come in, but elqoquent not attempt to use 'stats' as a column name in the insert?那么我怎样才能让我的统计信息进来,但 elqoquent 不尝试使用“统计信息”作为插入中的列名?
Using the save()
method, you can create a new Player
object and save it, and then create a new Stat
object and save it as a Player
related stats()
:使用save()
方法,您可以创建一个新的Player
对象并保存它,然后创建一个新的Stat
对象并将其保存为与Player
相关的stats()
:
$player = new Player
$player->name = $request->input('name');
$player->lastname = $request->input('lastname');
$player->save();
$stat = new Stat([
'position' => $request->input('stats.position'),
'profile' => $request->input('stats.profile'),
]);
$player->stats()->save($stat);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.