Laravel:检查MySQL查询是否有结果

6

首个 Laravel 项目。我有一个控制器函数,它检查是否有使用该条形码的记录。如果没有,则插入一条记录。如果有,则将计数加一。

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);

当我尝试它时,出现了以下错误:

SellController.php的第17行ErrorException:mysqli_num_rows()期望参数1为mysqli_result,但提供了数组

我做错了什么?


在这里,您不应该使用mysqli_num_rows或任何mysqli相关函数。 Laravel使用PDO。虽然为了论证,如果您想查看返回的行数,可以只计算结果数组中的值的数量... $row_cnt = count($test); - Jonathon
4个回答

12

在 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]);
}

如果您使用的是 Laravel 5.3 之前的版本,则查询构建器将返回一个数组。在这种情况下,您可以使用 php 的 count 函数来获取返回的行数。请注意保留 html 标签。
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]);
}

谢谢,但我又遇到了一个错误:"SellController.php"第17行的"FatalThrowableError":在数组上调用成员函数"isEmpty()"。 - Feralheart
在这种情况下,您可能使用的是低于5.3版本的Laravel。我已经更新了我的答案,并提供了这些版本的解决方案。 - Jerodev
我原以为我在使用5.3版本,但是现在我运行了'php artisan --version'命令,输出结果是'Laravel Framework 5.4.13'。我也尝试了第二个命令,“New row”可以正常工作,但是“Update”的输出是这个错误信息:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'o' at line 1 (SQL: o)。 - Feralheart

2
当我使用test->isEmpty()count($test) == 0时,仍然会收到以下错误信息:

Undefined offset: 0

因此,我最终使用以下方法检查DB::select返回的空值:
$test = DB::select('select count from sellmode where barcode = ?', [$barcode]);

if(collect($test)->first()) {
    // ...
} else {
    $response = new \stdClass();
    $response->error = true;
    $response->message = 'Sellmode not found';
    return response(json_encode($response))->header('Content-Type','application/json');                
}

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');
}

不知道你使用的是哪个版本,但是请查看文档:https://laravel.com/docs/5.4/eloquent - Ulrik McArdle

0

三个优雅的Laravel集合方法是isEmpty()、count()和first()。在Laravel中,不再需要使用vanillaPHP来计数。

$result = Model::all();
// if your resultset has something
if ($result->isEmpty()) // return false
if ($result->count() > 0) // return false
if ($result->first()) // return model object

// if your resultset has no entries
if ($result->isEmpty()) // return true
if ($result->count() > 0) // return true
if ($result->first()) // return null

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接