Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Two Level Relation Query

I have a DB structure...

Labels -> LabelPerson <- People -> Samples

I also have all needed relations in my Models. How can I get all samples ids, when I know only the label_id?

Label

public function people()
{
    return $this->belongsToMany('App\Person');
}

Person

public function labels()
{
    return $this->belongsToMany('App\Label')->withTimestamps();
}
public function samples()
{
    return $this->hasMany('App\Sample');
}

Sample

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

I try to use hasManyThrough relation in the Label model

public function samples()
{
    return $this->hasManyThrough('App\Sample', 'App\Person');
}

But no result...

Column not found: 1054 Unknown column 'people.label_id' in 'field list' (SQL: select samples.*, people.label_id from samples inner join people on people.id = samples.person_id where people.label_id = 2)",

I'm using Laravel 5.7.9.

like image 593
Teretto Avatar asked Mar 15 '26 04:03

Teretto


1 Answers

You can get them using whereHas() method, this provide you filter records by relation

Sample::whereHas("person.labels",function ($query) use ($label_id){
      $query->where("label_id",$label_id);
    })->get()->pluck("id");         
like image 105
Teoman Tıngır Avatar answered Mar 17 '26 17:03

Teoman Tıngır



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!