当条件为真时,Laravel在模型上返回空关系 [英] Laravel return empty relationship on model when condidtion is true
本文介绍了当条件为真时,Laravel在模型上返回空关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型,当发生条件时,我想在其中返回一个空值,但是当我尝试获取模型时:
I have a model where I want to return a empty value when a condition happens, but when I try to get the model:
Model::with('shop')->find(id);
我收到此错误:
对成员函数addEagerConstraints()的调用为空"
"Call to a member function addEagerConstraints() on null"
这是我正在尝试的代码:
This is the code I'm trying:
public function shop(){
if(true) {
return null;
}
return $this->belongsTo('App\Models\Shop');
}
当Laravel关系中的条件为真时,什么都不返回的正确方法是什么?
How is the proper way to return nothing when a condition is true on Laravel relationships?
推荐答案
我认为您可以使用此技巧-在满足条件时设置不可能的查询条件:
I think you could use this trick - set an impossible query condition when a condition met:
public function shop(){
return $this->belongsTo('App\Models\Shop')->where(function($query) {
if ($condition) {
// I think this should do the trick
$query->whereNull('id');
}
});
}
这篇关于当条件为真时,Laravel在模型上返回空关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文