hunterhawley
3 months ago

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

Posted 3 months ago by hunterhawley

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.

Please sign in or create an account to participate in this conversation.