2017-06-02 70 views
1

我在保存Eloquent模型时遇到了问题。例如:PHP Laravel 5.4.21。雄辩地将插入保存在第一行

$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请求完美,如Eloquent create()

回答

1

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']); 
+0

检查是否存在在调用此代码的包装函数中。有没有办法只得到选定的列,而不是所有的列? –

+0

@JonnySmith因为你所做的只是更新,没关系。这是更好的保持代码清洁。如果你想选择列,然后检查我的编辑答案 – Sandeesh

+0

问题仍然存在。它仍然插入第一个。是否可以将“id”放在$守护的位置? –

0

请尝试以下

$game = Game::find($id); 
$game->bank += $game->bet; 
$game->quantity_of_players++; 
$game->save(); 
+0

而且没有其他方法可以选择所需的列吗?因为它不太可能获得所有列。 –

+0

我猜的是,既然你不选择所有的东西,它会再次插入,因为laravel不会100%在db中找到模型。 (我认为) –

+0

有一个包装器,它包含这个代码的调用函数,并检查包装器中的行是否存在。所以必需的行总是存在。例如,我得到id = 2的行,并插入id = 2的行,而不是它。它总是插入id = 1的行。 –