0

I have a query like this:

    $query = "Select EXISTS(SELECT * FROM grp_user AS pivot JOIN groups
AS g ON pivot.grp_id = g.id JOIN vote ON g.id = vote.grp_id WHERE 
pivot.grp_id = :grp_id AND pivot.user_id = :user_id)";

and I want to run it . so I tried:

$res = DB::select($query,array("grp_id"=>250,"user_id"=>1));

res ideally should have a boolean value, but instead it has an array like :

[{"EXISTS(SELECT * FROM grp_user AS pivot JOIN groups AS g ON pivot.grp_id = g.id JOIN vote ON g.id = vote.grp_id WHERE pivot.grp_id = ? AND pivot.user_id = ?)":1}]

Note the 1 at the end, that is the value I'm interested in (its either 1 or 0).

How can I make this work , or achieve this the 'laravel' way ?

harveyslash
  • 5,906
  • 12
  • 58
  • 111
  • Is it still a `Builder` object? What does the result of `dd($res)` return? Have you tried adding a `->first()` or `->get()` to the end of `$res = DB::select();`? – Tim Lewis Jun 29 '16 at 15:59
  • its an array. when I append ->get() , i get error Call to a member function get() on array – harveyslash Jun 29 '16 at 16:11
  • why not just `SELECT COUNT(*) FROM grp_user AS pivot JOIN groups AS g ON pivot.grp_id = g.id JOIN vote ON g.id = vote.grp_id WHERE pivot.grp_id = :grp_id AND pivot.user_id = :user_id` ? – Alex Jun 29 '16 at 16:19
  • in this answer: http://stackoverflow.com/questions/1676551/best-way-to-test-if-a-row-exists-in-a-mysql-table , select exists was the fastest . this query that I mentioned will be called an extremely high number or times (its a way to authorise a user in a group messaging system) , so I want as much performance as I can get – harveyslash Jun 29 '16 at 16:22

1 Answers1

0

Why not just check if it is empty or not:

$query = "Select * FROM grp_user AS pivot JOIN groups
AS g ON pivot.grp_id = g.id JOIN vote ON g.id = vote.grp_id WHERE 
pivot.grp_id = :grp_id AND pivot.user_id = :user_id LIMIT 1";

$res = DB::select($query,array("grp_id"=>250,"user_id"=>1));

return (count($res) > 0) ? 1 : 0;
Alex Harris
  • 6,172
  • 2
  • 32
  • 57