dimanche 23 juin 2019

Having vs. Where in SQL, using the ORM in Laravel

I think my question is more related to SQL than to Laravel or its ORM, but I'm having the problem while programming in Laravel, so that's why I tagged it in the question.

My problem is as follows, I have the following model (sorry for the Spanglish):

enter image description here

  • I have the users table, nothing special here,
  • Then the juegos (games) tables, in it there's a jornada column (its like the week, to know which games are played in a certain week)
  • And finally the pronosticos (who the user says will win, which is stored in the diferencia column)

So I want to make a form where the user can make his bet. Basically this form will take its data from the pronosticos table, like this:

$juegos = Juego::where('jornada', $jor)
                 -> orderBy('expira')
                 -> get();

This produces what I want, a collection of models that I can iterate to show all the games for a given jornada (week).

Now, if the user has already make its bet, I want to bring also the scores values the user is betting on, with a query, so I thought I could use something like:

$juegos = Juego::where('jornada', $jor)
                  -> leftJoin('pronosticos', 'juegos.id', '=', 'pronosticos.juego_id')
                  -> addSelect(['pronosticos.user_id', 'juegos.id', 'expira', 'visitante', 'local', 'diferencia'])
                  -> having('pronosticos.user_id', $uid)
                  -> orderBy('expira')
                  -> get();

Now, the problem is, it is bringing an empty set, and thats quite obvious, if the user has made his bet, it will work, but if he hasn't the having will filter out everything, giving the empty set.

So I think I'm not getting clearly how to make the having or where to work correctly. Maybe what I want is to do a leftJoin not with the pronosticos table, but from the pronosticos table already filtered with a where clause.

Maybe I'm doing everything wrong and should do the leftJoin to a subselect? If that's so, I have no idea how to do it.

Or maybe my expectations are outside what can be done to SQL and I may return two different sets, and process them in the app?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire