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

Tro*_*yer 1 relationship laravel laravel-5 laravel-5.1

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

Model::with('shop')->find(id);
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

“在null上调用成员函数addEagerConstraints()”

这是我正在尝试的代码:

public function shop(){
    if(true) {
        return null;
    }
    return $this->belongsTo('App\Models\Shop');
}
Run Code Online (Sandbox Code Playgroud)

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

pab*_*rsk 7

返回BelongsTo实例的正确方法。

public function shop(): BelongsTo
{
    if(true) {
        return new BelongsTo($this->newQuery(), $this, '', '', '');
    }
    return $this->belongsTo('App\Models\Shop');
}
Run Code Online (Sandbox Code Playgroud)


Lio*_*han 5

我认为您可以使用此技巧-在满足条件时设置不可能的查询条件:

public function shop(){

    return $this->belongsTo('App\Models\Shop')->where(function($query) {

        if ($condition) {

            // I think this should do the trick
            $query->whereNull('id');
        }

    });

}
Run Code Online (Sandbox Code Playgroud)


Dig*_*ter 5

将您的查询包装在救援助手中:

// continue processing if an exception happens.
// return some default value if the query does not succeed, null for example.
return rescue(function () {
    // some custom logic here
    return $this->belongsTo('App\Models\Shop');
}, null);
Run Code Online (Sandbox Code Playgroud)

更新

对于 5.1 尝试返回一个新的模型实例:

public function shop(){
    if(true) {
        return new static;
    }
    return $this->belongsTo('App\Models\Shop');
}
Run Code Online (Sandbox Code Playgroud)

更新2

尝试返回模型的查询生成器

public function shop(){
    if(true) {
        return $this->newQuery(); // or newQueryWithoutScopes()
    }
    return $this->belongsTo('App\Models\Shop');
}
Run Code Online (Sandbox Code Playgroud)