如何使用查询构建器或原始SQL之间的关系

时间:2021-10-22 20:16:45

I'm using Laravel's Eloquent ORM, but want to define a complex relationship and was wondering if it were possible to use the query builder or raw SQL when defining a relationship.

我使用的是Laravel的有力的ORM,但是想要定义一个复杂的关系,并且想知道在定义关系时是否可以使用query builder或原始SQL。

This is the schema:

这是模式:

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.

表:objects_users;关系:许多tomany——一个对象可以由许多用户拥有,用户可以拥有许多对象。

Using a traditional relationship would work fine for normal records, ones that are entered individually into the pivot table. However, I also want to return additional results depending on additional criteria; i.e. allow all objects to belong to a user if they have a debugger flag set. Essentially, I want to mimic this query:

使用传统的关系对于正常的记录来说是可行的,这些记录是分别输入到pivot表中的。但是,我还想根据其他标准返回额外的结果;也就是说,如果所有对象都设置了调试器标志,则允许它们属于用户。

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 this can't be done, is it possible to return eloquent models from a query builder query?

或者,如果不能这样做,是否可能从查询生成器查询返回有说服力的模型?

1 个解决方案

#1


5  

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 raw result-Objects to your specified Model like that:

之后,您可以将原始结果对象“转换”到指定的模型,如下所示:

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

Hope this will help you! Have a nice christmas anyway ;)

希望这能对你有所帮助!祝你圣诞快乐!

#1


5  

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 raw result-Objects to your specified Model like that:

之后,您可以将原始结果对象“转换”到指定的模型,如下所示:

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

Hope this will help you! Have a nice christmas anyway ;)

希望这能对你有所帮助!祝你圣诞快乐!