gpt4 book ai didi

当条件为真时,Laravel 在模型上返回空关系

转载 作者:行者123 更新时间:2023-12-03 22:57:51 27 4
gpt4 key购买 nike

我有一个模型,我想在条件发生时返回一个空值,但是当我尝试获取模型时:

Model::with('shop')->find(id);

我收到此错误:

"Call to a member function addEagerConstraints() on null"



这是我正在尝试的代码:
public function shop(){
if(true) {
return null;
}
return $this->belongsTo('App\Models\Shop');
}

当 Laravel 关系中的条件为真时,如何正确地不返回任何内容?

最佳答案

我认为你可以使用这个技巧——在满足条件时设置一个不可能的查询条件:

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 在模型上返回空关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49811825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com