在急切加载 Laravel 时调用未定义的方法 Illuminate\Database\Query\Builder::isEmpty

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48467363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:18:04  来源:igfitidea点击:

Call to undefined method Illuminate\Database\Query\Builder::isEmpty on eager loading laravel

phplaravellaravel-5.5

提问by A.B.Developer

I have a Cartmodel like this :

我有一个Cart这样的模型:

class Cart extends Model
    {
        protected $table = 'cart';

        protected $fillable = ['user_id', 'delivery_method'];

        public function products ()
        {
            return $this->belongsToMany(Product::class, 'cart_products', 'cart_id', 'product_id')->withPivot('quantity');
        }

    }

And carttable columns are :

表列如下:

id
user_id
delivery_method
created_at
updated_at

And there is a pivot table named cart_productsto relate Cardmodel to a ProductModel.

并且有一个名为cart_productsCard模型与模型相关联的数据透视表Product

Suppose I have an specific $user_idvariable. now I want Cart with that user_id with their products. for that I wrote this :

假设我有一个特定的$user_id变量。现在我想要带有那个 user_id 的 Cart 和他们的产品。为此我写了这个:

$cartWithProducts = Cart::with('products')->where(['user_id' => $user_id])->first();

if (!$cartWithProducts->isEmpty()) {
//Some codes come here
}

But after run, I got this error :

但运行后,我收到此错误:

Call to undefined method Illuminate\Database\Query\Builder::isEmpty() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method Illuminate\Database\Query\Builder::isEmpty() at D:\wamp\www\barlly\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php:2461

I do not want to use lazy loadingapproach beacause n queryproblem. what is solution in this case?

我不想使用延迟加载方法,因为n 查询问题。在这种情况下解决方案是什么?

Also each User can have only one Cart in time.

此外,每个用户在时间上只能有一个购物车。

回答by ATechGuy

you can just call

你可以打电话

if ($cartWithProducts) {
//Some codes come here
}

Have a read over this Answer

仔细阅读这个 答案

回答by patriziotomato

Expecting your can have multiple carts for specified users and you may proceed more than one I would recommend to do something like this:

期望您可以为指定用户拥有多个购物车,并且您可以进行多个购物车,我建议您执行以下操作:

$cartWithProducts = Cart::whereUserId($user_id)->with('products')->get();

if ($cartWithProducts->isNotEmpty()) {
    //Some codes come here
}

回答by Alexey Mezenin

first()returns nullif there is no Cart for the user, so if you want to check if it's empty, you can use is_null()or empty()instead of if (!$cartWithProducts)to keep is readable:

first()null如果用户没有购物车,则返回,因此如果您想检查它是否为空,您可以使用is_null()empty()代替if (!$cartWithProducts)保持可读:

if (is_null($cartWithProducts))