Query Builder acts like eloquent

  eloquent, laravel, laravel-query-builder, php, query-builder

I just want to know, can I create ‘eloquent relationship’ using query builder on Laravel. Is there a way to do that?

Example:

I have two table

users
========
user_id
user_name

events
========
event_id
event_name
user_id

I know that if I want to select event and want to show the user who create the event I can do it like this

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class User extends Model
{
    public function events() {
        return $this->belongsTo(Event::class, 'user_id', 'user_id');
    }
}

In Controller I can just call it like this

User::find(1)->with('events');

But In this case I have a complex query and join 3 table, I’m afraid about the complexity so I want to make it only using query builder not eloquent but is there a way to make it like the eloquent behaviour?

Expectation: (I know its a wrong query but is there a way to make it ?)

DB::select('select * from users where user_id = ?', [1])->with('events');

Example Expected Result:

user: {
    user_id: 1,
    user_name: 'Mr. Man',
    events: [
        {
            event_id: 1,
            event_name: 'Birthday Party'
        },
        {
            event_id: 2,
            event_name: 'Honey Moon'
        }
    ]
}

Source: Laravel

Leave a Reply