Laravel 6 在 belongsTo 关系上使用 with() 进行预加载只是*有时*返回 null

Laravel 6 eager loading using with() on a belongsTo relationship is only *sometimes* returning null

我正在做一个项目,我们有一个服务提供商模型、提供的护理类型和状态:

提供商:

class Provider extends Model
{
    protected $table = 'providers';

    public function status() {
        return $this->belongsTo('App\Status');
    }

    public function caretype() {
        return $this->belongsTo('App\CareType', 'id');
    }
}

护理类型:

class CareType extends Model
{
    protected $table = 'type_of_care';

    public function providers() {
        return $this->hasMany('App\Providers', 'type_of_care_id');
    }

    public function category() {
        return $this->belongsTo('App\CareCategory');
    }
}

状态:

class Status extends Model
{
    protected $table = 'status';

    public function providers() {
        return $this->hasMany('App\Providers');
    }
}

在 my SearchController(处理提供者搜索请求的控制器)上,使用预先加载的 show() 函数完美地检索 caretype。但是在列出搜索结果集合的 search() 函数中,caretype 总是被列为 null。

我不明白为什么它会在一个函数中工作而不在另一个函数中工作,尤其是当两个函数中预加载的代码完全相同时:

public function search(Request $request)
    {

        $validated = $request->validate([
            //I removed the validation code for this post
        ]);

        $providers = Provider::with(['status', 'caretype'])->get();

        return view('search.results', ['providers' => $providers]);

    }

    public function show($id)
    {

        $single_provider = Provider::with(['status', 'caretype'])->where('id', $id)->first();
        return view('search.details', ['provider' => $single_provider]);

    }

如有任何帮助,我们将不胜感激。我知道模型和关系外键已正确定义,因为 show() 函数能够很好地获得 caretype

不。您的关系和外键不正确。从 doc

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column. However, if the foreign key on the Child model is not like that, you may pass a custom key name as the second argument to the belongsTo method.

您在 Provider 模型的 caretype 关系中将 id 列作为外键传递,但您的外键是 type_of_care_id。所以当 id 匹配时你会得到一些结果,但如果不匹配,你就会得到 null。将您的关系代码更改为

public function caretype()
{
    return $this->belongsTo('App\CareType', 'type_of_care_id');
}

现在再次来自文档

If your parent model does not use id as its primary key, or you wish to join the child model to a different column, you may pass a third argument to the belongsTo method specifying your parent table's custom key.

在你的例子中 id 是主键。所以你不必传递第三个参数。只需更新主键引用,一切都会完美运行。