Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 雄辩-插入相关模型_Php_Laravel_Eloquent - Fatal编程技术网

Php 雄辩-插入相关模型

Php 雄辩-插入相关模型,php,laravel,eloquent,Php,Laravel,Eloquent,在此情况下,保存相关模型的公认答案是: public function store(Request $request) { $player->name = $request->input('name'); $player->lastname = $request->input('lastname'); $player->stats = [ 'position' => $request->input('stats.pos

在此情况下,保存相关模型的公认答案是:

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);
}
每当我尝试此操作时,都会出现一个错误:

未找到列:字段中的1054未知列“stats” 列表'

如果我把统计数据添加到防护集合中,它当然不会出现

在我的玩家对象上,我有:

public function stats(): HasMany
{
    return $this->hasMany(Stat::class);
}
那么,我如何才能获得我的统计数据,但elqoquent不尝试在插入中使用“stats”作为列名?

使用
save()
方法,您可以创建一个新的
Player
对象并保存它,然后创建一个新的
Stat
对象并将其保存为
Player
相关的
stats()


它没有插入到相关模型中。它只是在对象中添加了一个array/json列。选中此项以保存相关模型。谢谢,我已经读过了,其中提到从数据库中提取一个对象,向其中添加相关对象,然后推送它。我找不到它解决了我的情况,我正在一起创建父项和子项,这似乎是我链接的答案使用
$player->save()
不,你搞错了。您链接的答案仅适用于单个对象。你需要两个。查看下面提供的答案。这就是我最后所做的,尽管我仍然对我所链接的问题的答案感到困惑,因为它似乎表明这可以一步完成。(这是我在.net项目中使用Entity Framework时所习惯的)嗯,不,要创建相关的统计数据,您需要播放器
id
,因此您必须在DB中插入播放器,使其具有
id
。我认为您可以使用
create()
方法在一行中完成,并将相关的stat
create
链接到播放器
create
。但同样,您必须始终先插入播放机。
$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);