Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Čamo's avatar
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.

0 likes
3 replies
martinbean's avatar

@Čamo You don’t. Relations is something offered by an ORM, i.e. Eloquent. The DB facade is just for running raw SQL queries. There’s no such things as “relationship” in raw SQL.

So, if you want relations in your code, use Eloquent.

Čamo's avatar
Level 3

I wrote a package. It works with Eloquent query builder but I would like to make it also for DB query builder. I am not sure now.

Please or to participate in this conversation.