php Laravel 在创建 Eloquent 对象时从空值创建默认对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24224411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Creating default object from empty value when creating an Eloquent object
提问by Chris
I'm trying to save an object to the database for a game I'm building on a website, but I keep getting this error:
我正在尝试将一个对象保存到我在网站上构建的游戏的数据库中,但我不断收到此错误:
Creating default object from empty value
Here's the code I'm using:
这是我正在使用的代码:
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();
}
The error occurs at the if statement. I tried commenting it out, and then the error occurred at the $item->game_id = $game->id; line.
错误发生在 if 语句中。我试着把它注释掉,然后错误发生在 $item->game_id = $game->id; 线。
I've var_dumped both $item and $game, and both are valid Eloquent objects. I even var_dumped the result of the if statement with no problems, so I'm at a loss as to what's happening.
我已经对 $item 和 $game 进行了 var_dump,它们都是有效的 Eloquent 对象。我什至 var_dumped if 语句的结果没有任何问题,所以我对发生的事情感到茫然。
I just noticed if I do
我只是注意到如果我这样做
var_dump($item->toArray()); die();
right before the $item->save(); line, it doesn't throw any errors and shows me the array just fine.
就在 $item->save() 之前;行,它不会抛出任何错误并向我显示数组就好了。
What could be the problem then? I suppose it has to do with saving the item, but I don't understand it at all.
那可能是什么问题呢?我想这与保存项目有关,但我根本不明白。
采纳答案by The Alpha
The following line:
以下行:
$item = ($input['itemIDs'][$key] === 'NA') ? new GameItem() : GameItem::find($input['itemIDs'][$key]);
Always doesn't return a GameItem
object so when you try to use a property
on NULL
value then this error appears. So you should always check if the $item
is not NULL
using something like this:
始终不返回GameItem
对象,因此当您尝试使用property
onNULL
值时,会出现此错误。所以你应该总是检查是否$item
没有NULL
使用这样的东西:
if( !is_null($item) && $item->game_id != $game->id ) { continue; }
Instead of this (At first make sure $item
is not NULL
before you use $item->game_id
):
而不是这个(首先确保$item
不是NULL
在你使用之前$item->game_id
):
if( !is_null($item->game_id) && $item->game_id != $game->id ){ continue; }