拉拉维尔雄辩 仅检索基于关系字段的某些行


Laravel Eloquent Retrieving only certain rows basing on relation field

我有许多模型,我相信我的关系设置正确。

我想从表中检索所有模型,当且仅当外键表的active列为真时。

我已经尝试了许多变化,但无济于事。

以下是设置。

该表称为device,它指向一个名为dep的表。

DEVICE模型与 DEP 具有以下关系

public function dep() {
    return $this->belongsTo('App'Dep');
}

DEP模型有一个名为 active 的列,该列设置为 truefalse

我应该使用什么雄辩的命令来返回DEP表的active字段为真的所有Devices

目前,我必须获取所有DEP模型,然后仅在活动字段设置为 true 时才获取设备,但我相信必须有一种更优雅的方法。

谢谢。

如果要

根据相关模型中字段的存在来限制结果,则需要查看whereHas方法。

$devices = Device::whereHas('dep', function($query) {
    $query->where('active', '=', true); // Replace true with 1 if you aren't using casts
})->get();

这将获取具有active字段 true 的dep的所有设备。不过,这不会与Device一起获取dep。如果你想要这样,那么只需像往常一样使用带有预先加载的whereHas

$devices = Device::with('dep')->whereHas('dep', function($query) {
    $query->where('active', '=', true);
})->get();

您可以简单地为您的关系添加一个过滤器:

public function dep() {
    return $this->belongsTo('App'Dep')->where('active', true);
}

或者,如果您希望保持dep关系不变,则可以考虑添加另一个关系以仅检索活动模型:

public function depActive() {
    return $this->belongsTo('App'Dep')->where('active', true);
}

这将返回与Device相关的所有DEP模型,具有active = 1

您可以按如下方式使用该关系:

$depActives = $device->depActive;

$depActives = $device->depActive()->get();

他们中的Boh也会这样做