Laravel Results of a Query Builder for eloquent model

Asked

Viewed 1,810 times

5

I am making 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, however it returns me 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 methods of relation, I was able to loop the results and put them in a Collection but when I try to create an Eloquent Object Model from my stdClass object, the Eloquent model doesn’t seem to work as it should not be able to query the relationship methods

1 answer

3

One way would be to select only the user ids in your Builder query 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

Then make a call to the User model as it would have access to relations.

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

But this will generate more queries than you would need. Using Eloquent is an option of code practicality but sometimes has the consequence of increasing the number of queries.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.