在Laravel中判断表是否为空

10 浏览
0 Comments

在Laravel中判断表是否为空

我正在尝试找出我的表是否为空,但是我遇到了这个错误

调用未定义函数App\\Http\\Controllers\\isEmpty()

我检查了和我的标题相似的问题,但没有我需要的东西。

这是我的代码

$orders = Order::all();
if(isEmpty($orders))
{
    echo "Im empty";
    die();
 }else{
    echo "im not empty";
     die();
 }

admin 更改状态以发布 2023年5月20日
0
0 Comments

好的,既然这里的所有答案都不是 好的/优化过的,那么这是检查一个表是否有 任何行/表不为空 的最快方法:

$order = Order::first();
if(is_null($order)) {
    // Table is empty.
}else {
    // Table is not empty.
}

Order::all()Order::count() 是不好的,因为你的表可能有数百万条记录,当你获取所有行时,你可能会遇到内存异常甚至系统卡顿的问题

0
0 Comments

你应该使用 Model::exists()。它返回 true/false,并在底层运行一个 select count(*) from table where 查询。

if (Order::exists()) {
    echo "im not empty";
    die();
} else {
    echo "Im empty";
    die();
}

0