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

hunterhawley's avatar

Access relationship from inside a where clause (or however I'm supposed to do this)

Hey y'all! Quick question this morning. I've got two tables: 'stats' and 'stat_metas'. 'stat_metas' holds all the 'meta' information about a stat, like its name, description, that stuff. 'stats' holds actual instances of stats, referenced back to stat_meta (each stat has one stat_meta, each stat_meta has many stats).

I have another model though called Game, where I am working with these two tables. (Game has many stats, you get the picture)

From Game, I am using this to pull the number of times a stat with the stat_meta id of 3 comes up:

$twosMade = $this->hasMany('App\Models\Stat', 'game_id')->where('stat', '3')->count();

Note: 'stat' (as in where('stat', '3')) is the column name in the 'stats' table that references the id on the stat_metas table)

However, instead of using the id from stat_meta, I would like to use the name of the stat. I want to do something like this, however this is obviously wrong:

$twosMade = $this->hasMany('App\Models\Stat', 'game_id')->where('stat->stat_meta->stat_name', 'assist')->count();

Does anyone have an idea of how this should be approached? I wish I had a visual or something to show, when explaining these Eloquent relationships and whatnot I get pretty confused at times.

0 likes
2 replies
mvd's avatar

Hi @hunterhawley

I'm not 100% sure and not tested but hope you get an idea to get you started. You can set another relationship from a child relationship, example

->with('stats.stat_meta')

In your stats model create a relationship to stat_meta with method name stat_meta, example

function stat_meta() {
    return $this->hasMany(StatMeta::class);
}

If you want to filter on the stat_meta you could do something like

$games = App\Game::where('id', 3)->with(['stat.stat_meta' => function($q) {
    $q->where('stat_name', 'assist');
}]))->get();
hunterhawley's avatar

I think you are on the right track, but I'll have to keep working on this one. I've got a lot going on in my model that needs to be wrangled haha

Please or to participate in this conversation.