I am going to give an answer because the first solution from @meagar requires two SQL queries instead of one (also, is it not a SQL syntax error if there are no commands in the league?), And the second solution will contain duplicate game instances if both teams were from the same league.
In general, I try to avoid unions in my reusable areas, because they force the request to specify a certain "form". So I would write something like this:
class Game
This SQL method, by the way, is called a "correlated subquery." I admit that this looks weird the first time you see it, but it's a pretty normal thing. You can see that the subquery "reaches" for the games
link. Your database should not have problems with its optimization (taking into account the indexes on your foreign keys), but conceptually speaking, it performs a subquery once per row in the games
table.
source share