php - Laravel 在创建 Eloquent 对象时从空值创建默认对象

标签 php laravel eloquent

我正在尝试将一个对象保存到我在网站上构建的游戏的数据库中,但我不断收到此错误:

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/

相关文章:

migration - 在 Laravel 中为现有 InnoDB 关系设置 Eloquent 关系

php - 当通过 PHP 路由时,CSS 将无法通过 Heroku 工作

php - 如何制作反向对象?

php - 我如何在最多 4 个级别的树中选择类别

laravel - 如何在 Laravel 中在 MIN 和 MAX 之间搜索

php - 在 Laravel 中组合 orWhere 和 Where

php - 与 Laravel 在处理数百万条记录时使用 block 的普通查询构建器相比,Laravel Eloquents 和使用 block 是否更慢?

php - Laravel 5.2 Eloquent 列名称冲突

php - 根据时间戳字段之间的差异过滤 MySQL 查询

php - 从两个 Mysql 表中获取信息