2017-06-02 64 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的行。 –