我正在尝试将一个对象保存到我在网站上构建的游戏的数据库中,但我不断收到此错误:
Creating default object from empty value
这是我使用的代码:
foreach( $input['items'] as $key=>$itemText ){
$item = ($input['itemIDs'][$key] === 'NA') ? new GameItem() : GameItem::find($input['itemIDs'][$key]);
// if updating this item, check that it is assigned to this game
if( !is_null($item->game_id) && $item->game_id != $game->id ){ continue; }
$item->game_id = $game->id;
$item->item = $itemText;
$item->answer = $input['answers'][$key];
$item->save();
}
错误发生在 if 语句处。我试着把它注释掉,然后错误发生在 $item->game_id = $game->id;行。
我已经 var_dumped $item 和 $game,它们都是有效的 Eloquent 对象。我什至 var_dumped if 语句的结果没有任何问题,所以我不知道发生了什么。
我只是注意到如果我这样做了
var_dump($item->toArray()); die();
就在 $item->save(); 之前行,它不会抛出任何错误并向我显示数组就好了。
那可能是什么问题呢?我想这与保存项目有关,但我完全不明白。
最佳答案
下面一行:
$item = ($input['itemIDs'][$key] === 'NA') ? new GameItem() : GameItem::find($input['itemIDs'][$key]);
始终不返回 GameItem
对象,因此当您尝试在 NULL
值上使用 property
时,会出现此错误。所以你应该总是检查 $item
是否不是 NULL
使用这样的东西:
if( !is_null($item) && $item->game_id != $game->id ) { continue; }
取而代之(首先确保 $item
在使用 $item->game_id
之前不为 NULL
):
if( !is_null($item->game_id) && $item->game_id != $game->id ){ continue; }
关于php - Laravel 在创建 Eloquent 对象时从空值创建默认对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24224411/