How to use query builder or raw SQL in Laravel Rloquent relationships

I am using Laravel Eloquent ORM but want to define complex relationships and wondered if it is possible to use a query constructor or raw SQL when defining a relationship.

This is the diagram:

Table: objects; Model: Object

Table: users; Model: User

Table: objects_users; Relationship: ManyToMany - an object can be owned by many users, a user can own many objects.

Using traditional relationships will work fine for regular records that are entered individually into a PivotTable. However, I also want to return additional results based on additional criteria; those. allow all objects to be owned by the user if they have the debugger flag set. Essentially, I want to mimic this query:

SELECT objects.*
FROM objects
LEFT JOIN objects_users ON objects.id = objects_users.object_id
INNER JOIN users ON
    objects_users.user_id = users.id
    OR users.debugger = 1

      

Alternatively, if it cannot be done, is it possible to return eloquent models from a query builder query?

+3


source to share


1 answer


You can do something like this:

    $objects = DB::select('select objects.* from objects 
    LEFT JOIN objects_users ON objects.id = objects_users.object_id
    INNER JOIN users ON
    objects_users.user_id = users.id
    OR users.debugger = 1');`

      

After that, you can "convert" the original result-objects to the model you specify as follows:



$objArray = array();
$objArray = YourObjectModel::hydrate($objects);

      

Hope this helps you! Have a nice Christmas anyway;)

+5


source







All Articles