我在保存雄辩的模型方面有问题。例如:
$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');
});
}
真的很感谢它的任何帮助。
P.S。所有SELECT
请求都可以很好地工作,例如雄辩的create()
。
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']);
请尝试以下
$game = Game::find($id);
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();