我有许多模型,我相信我的关系设置正确。
我想从表中检索所有模型,当且仅当外键表的active
列为真时。
我已经尝试了许多变化,但无济于事。
以下是设置。
该表称为device
,它指向一个名为dep
的表。
DEVICE
模型与 DEP 具有以下关系
public function dep() {
return $this->belongsTo('App'Dep');
}
DEP
模型有一个名为 active
的列,该列设置为 true
或 false
。
我应该使用什么雄辩的命令来返回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也会这样做