我有一个数据库结构...
Labels -> LabelPerson <- People -> Samples
我的模型中也有所有需要的关系。当我只知道 label_id
时,如何获取所有 samples
id?
标签
public function people()
{
return $this->belongsToMany('App\Person');
}
人
public function labels()
{
return $this->belongsToMany('App\Label')->withTimestamps();
}
public function samples()
{
return $this->hasMany('App\Sample');
}
示例
public function person()
{
return $this->belongsTo('App\Person');
}
我尝试在 Label
模型中使用 hasManyThrough 关系
public function samples()
{
return $this->hasManyThrough('App\Sample', 'App\Person');
}
但是没有结果...
Column not found: 1054 Unknown column 'people.label_id' in 'field list' (SQL: select
samples
.*,people
.label_id
fromsamples
inner joinpeople
onpeople
.id
=samples
.person_id
wherepeople
.label_id
= 2)",
我正在使用 Laravel 5.7.9。
最佳答案
您可以使用whereHas()
方法获取它们,这为您提供了按关系过滤记录
Sample::whereHas("person.labels",function ($query) use ($label_id){
$query->where("label_id",$label_id);
})->get()->pluck("id");
关于php - Laravel 二级关系查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52791888/