Why do you need DB facade instead of Eloquent?
Aug 2, 2021
3
Level 3
How to get database relations via DB facade.
I need to use DB facade instead of Eloquent and does not know if is possible to get M:N relations as array. It seems DB simply returns first item in the collection.
In my case I have a articles table where one article has one user and user has many roles.
I have a query:
DB::table('articles')
->select('articles.*', 'users.created_at as ucreated_at',
'users.name as uname', 'users.id as uid', 'roles.name as rname'
)->where('articles.id', 79)
->join('users', 'articles.user_id', '=', 'users.id')
->join('users_roles', 'users_roles.user_id', '=', 'users.id')
->join('roles', 'users_roles.role_id', '=', 'roles.id')
->get();
I know that this can be rewritten to Eloquent, but it is only example.
As I wrote this seems to return only the first item in roles collection. Am I right? So how can I get articles with user and the related roles for each user?
Thanks for help.
Please or to participate in this conversation.