Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to LEFT JOIN?

** Edited for a better understandability **

** Edit renamed to Document **

I want to get all user Document records with vote records on them by given user, and if that user is not voted for some document records i still want to get all document records without votes. For egzample:

+------------+--------------+------+
|document.par1|document.par2| vote |
+------------+--------------+------+
|    2       | z            | y    |
|    3       | w            | NULL |
|    4       | x            | NULL |
+------------+--------------+------+

On Ruby on Rails if i tryed this:

I. firs try:

Document.
   joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id` AND `votes`.`giver_id` = ?", user_id).
   where('document.creator_id = ?', user_id, .....).
   select('votes.*', `document.param1')

i got this error:

RuntimeError in UserDocumentsController#show

unknown class: Fixnum

II. second try:

Document.
   joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
   where('document.creator_id = ? AND `votes`.`giver_id` = ?', user_id, user_id, .....).
   select('votes.*', `document.param1')

Returns only that records that have votes:

+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
|    2        | z           | y    |
+-------------+-------------+------+

So there is missing 2 records..

** Updated, this solution works **

III. My third try, thanks for help Mischa:

Document.
   joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
   where('document.creator_id = ? AND (`votes`.`giver_id` = ? OR  `votes`.`giver_id` IS NULL)', user_id, user_id).
   select('votes.*', `document.param1')

+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
|    2        | z           | y    |
|    3        | w           | NULL |
|    4        | x           | NULL |
+-------------+-------------+------+
like image 231
liutis Avatar asked Nov 15 '12 22:11

liutis


1 Answers

This will get you the result set you need:

Document.
   joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
   where('document.creator_id = ? AND (`votes`.`giver_id` = ? OR  `votes`.`giver_id` IS NULL)', user_id, user_id).
   select('votes.*', `document.param1')
like image 128
Mischa Avatar answered Sep 21 '22 17:09

Mischa