2017-03-03 64 views
3

第一個Laravel項目。我有一個控制器功能,檢查是否有條形碼記錄。如果沒有插入記錄。如果是,請爲計數添加一個。Laravel:檢查MySQL查詢是否有結果

public function sellmode(Request $request){ 
    $barcode=$request->barcode; 
    $test = DB::select('select count from sellmode where barcode = ?', [$barcode]); 
    $row_cnt = mysqli_num_rows($test); 
    if ($row_cnt == 0) { 
     Debugbar::info('Új sor'); 
     DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']); 
    } else { 
     Debugbar::info('Meglévő frissítése'); 
     DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]); 
    } 
    return view(sell); 

}

當我試了一下,它有以下錯誤:

ErrorException in SellController.php line 17: mysqli_num_rows() expects parameter 1 to be mysqli_result, array given

我是怎麼了?

+0

你不應該使用'mysqli_num_rows'或這裏的任何mysqli的相關功能。 Laravel使用PDO。儘管出於參數的原因,如果你想看看有多少行返回,你可以計算結果數組中的值的數量......'$ row_cnt = count($ test);' – Jonathon

回答

3

您不能只在Laravel查詢構建器上使用mysql_num_rows。 Laravel查詢生成器將返回一個collection,因此您可以使用isEmpty函數來確定它是否有任何結果。

if ($test->isEmpty()) { 
    Debugbar::info('Új sor'); 
    DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']); 
} else { 
    Debugbar::info('Meglévő frissítése'); 
    DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]); 
} 

如果您在5.3之前使用Laravel版本,查詢生成器將返回一個數組。在這種情況下,你可以使用這個陣列上的PHP count功能知道返回多少行

if (count($test) === 0) { 
    Debugbar::info('Új sor'); 
    DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']); 
} else { 
    Debugbar::info('Meglévő frissítése'); 
    DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]); 
} 
+0

謝謝,但我得到了另一個錯誤:「SellController.php中的FatalThrowableError第17行:調用成員函數isEmpty()on array」 – Feralheart

+0

在這種情況下,您可能使用的Laravel版本低於5.3。我已經用這些版本的解決方案更新了我的答案。 – Jerodev

+0

我想,我使用5.3,但現在我運行'php artisan --version',輸出結果是'Laravel Framework 5.4.13'。我嘗試了第二個命令,「新行」正在工作,但「更新」的輸出是這個錯誤消息:SQLSTATE [42000]:語法錯誤或訪問衝突:1064您的SQL語法錯誤;請檢查與您的MySQL服務器版本相對應的手冊,以獲得在第1行'o'附近使用的正確語法(SQL:o) – Feralheart

2

這將是建立一個模型,並用它來查詢數據庫是一個好主意。也許這樣的事情(在我看來,這是比較容易的方式):

$sellMode = SellMode::where('barcode', $barcode)->get(); 
if($sellMode->isEmpty()){ 
    Debugbar::info('Új sor'); 
    $sellMode = SellMode::create(['barcode' => $barcode, 'count' => 1]); 
} 
else{ 
    Debugbar::info('Meglévő frissítése'); 
    $sellMode->increment('count'); 
} 
+0

不知道您使用的是哪個版本,但請查看文檔:https:/ /laravel.com/docs/5.4/eloquent –