Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Miko55's avatar

One to many realationship with where query

I have two tables, one is Scores and other one is Leagues.

In Leagues I have ID, LeagueName

In Scores I have ID, league_id, user_id, points

class League extends Model
{
    public function scores(){
        //return $this->hasMany(Score::class,"user_id","id");
        $this->hasMany(Score::class,'league_id');;
    }
}
class Score extends Model
{
    public function user(){
        return $this->belongsTo(User::class,'user_id');
    }

    public function league(){
        return $this->belongsTo(League::class,'league_id');
    }
}

This two are my models. Now I want to make a Eloquent query where I would filter Scores by LeagueName. I tried bunch of things, but they didn't work.

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

something like

$filteredScores = Scores::whereHas('league', function($query) use($leaguename) {
    $query->where('LeagueName',$leaguename);
})->get();

or if you have the league model as $league

    $leaguescores = $league->scores;

Please or to participate in this conversation.