在急切加载 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
Call to undefined method Illuminate\Database\Query\Builder::isEmpty on eager loading laravel
提问by A.B.Developer
I have a Cart
model 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_products
to relate Card
model to a Product
Model.
并且有一个名为cart_products
将Card
模型与模型相关联的数据透视表Product
。
Suppose I have an specific $user_id
variable. 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
回答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 null
if 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))