Laravel Results of a Query Builder for eloquent model

5

I'm doing a query using Query Builder

$users = DB::select( DB::raw("
SELECT users.* from users, permissions_customers WHERE
permissions_customers.customer_id in 
(
  SELECT permissions_customers.customer_id from 
  permissions_customers
  WHERE 
  permissions_customers.user_id = ?
)
AND
permissions_customers.user_id = users.id
GROUP BY users.id
"), array(5));

As you can see in T-SQL the return is a result of the users table, but it returns an array of objects of type stdClass, I would like these results to be a list (Collection) of Eloquent Model for me to access its relationship methods, I was able to loop in the results and put them in a Collection but but when I try to create an Eloquent Model Object from my stdClass object, the Eloquent model does not seem to work as it should I can not do queries on the methods

    
asked by anonymous 05.09.2014 / 14:50

1 answer

3

One way is to select only the user ids in your query builder and mount an array with the result

// users.* alterei para users.id
$users = DB::select( DB::raw("
    SELECT users.id from users, permissions_customers etc...etc...
    GROUP BY users.id
"), array(5));

$users_ids = (array) $users; // talvez não funcione esta linha

Next, make a call to the User model so that it would have access to the relations.

$users = Users::whereIn('id', $users_ids)->get();

But this will generate more queries than it would need. Using Eloquent is an option for code convenience but sometimes has the effect of increasing the number of queries.

    
19.09.2014 / 22:05