PHPLaravel5.4.21。雄辩的第一行保存插入

PHPLaravel5.4.21。雄辩的第一行保存插入,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,我对保存有说服力的模型有问题。例如: $game = Game::select(['bank', 'state', 'quantity_of_players'])->find($id)->first(); $game->bank += $game->bet; $game->quantity_of_players++; $game->save(); 据我在文档中所知,save()应该在$id的行中插入更改后的值,但它会插入第一行。问题是什么,以及如何将其正确保

我对保存有说服力的模型有问题。例如:

$game = Game::select(['bank', 'state', 'quantity_of_players'])->find($id)->first();
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();
据我在文档中所知,
save()
应该在
$id
的行中插入更改后的值,但它会插入第一行。问题是什么,以及如何将其正确保存到指定行中的数据库

此模型的迁移:

 public function up()
{
    Schema::create('games', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->enum('state', ['wait', 'search', 'accept', 'play', 'finish']);
        $table->smallInteger('quantity_of_players');
        $table->smallInteger('ready_players');
        $table->smallInteger('finished_players');
        $table->integer('bank');
        $table->smallInteger('bet');
    });
}
我真的非常感谢你在这方面的帮助


另外,所有
SELECT
请求都能完美地工作,例如雄辩的
create()

请尝试以下操作

$game = Game::find($id);
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();
find()
方法在内部调用
first()
。在继续之前检查行是否存在也是一种很好的做法。使用
findOrFail()

$game = Game::findOrFail($id);
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();
编辑

如果您坚持要为更新选择列。那就这样做吧

$game = Game::whereId($id)->first(['bank', 'state', 'quantity_of_players']);

没有其他方法来选择所需的列吗?因为它不太可能得到所有的列。我猜,因为你没有选择所有的列,它会再次插入,因为laravel没有100%在数据库中找到模型。(我认为)有一个包装器,它调用包含此代码的函数,并检查包装器中是否存在行。所以必需的行始终存在。例如,我获取id=2的行,然后插入id=2的行,而不是它。它总是插入id=1的行中。您可以尝试使用批量更新,这样就不会出现问题,但我不认为获取每一列确实是一个问题。检查是否存在于调用此代码的包装函数中。有没有办法只获取选定的列,而不是所有列?@JonnySmith因为你所做的只是更新,这没关系。这对于保持代码干净来说是最好的。如果您想要选定的列,请检查我对答案的编辑问题仍然存在。它仍然是第一个插入。是否将“id”放在$guarded中会导致此问题?
$id
的内容是什么?获取游戏模型并发布结果后,是否可以运行
dd($game)
$guarded
属性不是问题。“Id”是一个增量<代码>游戏{#154+时间戳:false#守护:数组:1[0=>“id”]#可填充:数组:6[0=>“状态”1=>“玩家数量”2=>“准备好的玩家”3=>“完成的玩家”4=>“银行”5=>“赌注”]+存在:true+最近创建的:false#属性:数组:7[“id”=>1“状态”=>“等待”“玩家数量”=>0“准备玩家”=>0“完成玩家”=>0“银行”=>30“下注”=>30]