在Laravel 5中,如何从相关表中获取属性作为其自身表的属性? [英] How does one get properties from related table as properties of it's own table in Laravel 5?

查看:32
本文介绍了在Laravel 5中,如何从相关表中获取属性作为其自身表的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题听起来有点令人困惑,但我不知道如何用一句话更好地解释它.

The question might sound a little bit confusing but I don't know how to explain it better in one sentence.

这基本上描述了问题所在:

This describes basically what the problem is:

我有一个Users表,其中可以包含2种类型的用户.我知道我该如何按角色分开.但是,事实是,角色1(editor_in_chief)的用户与角色2(reviewer)的用户具有不同的属性.

I have a Users table which can contain 2 types of users. I know how I can separate by role. But here's the thing, users with role 1(editor_in_chief) have different attributes than users with role 2(reviewer).

我的想法是创建一个名为"reviewer_attributes"和"editor_in_chief_attributes"的表,并与该表建立一对一关系,以保存用户表的属性.

My idea was to create a table named 'reviewer_attributes' and 'editor_in_chief_attributes' and create a one-to-one relation with this table to hold the attributes for the users table.

也许您有一个更好的主意,那也很好.但是对于这种情况,我想知道是否可以调用数据库并从另一个表中获取这些用户的属性作为User对象的属性.

Maybe you have a better idea, that would be great as well. But for this scenario, I would like to know if it is possible to make a call to the database and to get these users' properties from the other table as properties of the User object.

在使用关系调用进行数据库调用时,laravel会给我这样的信息:

When using a DB call using relations laravel will give me something like this:

user {
   id: 1,
   name: "Name",
   reviewer_attributes: {
      attribute_1: 'attribute_1',
      attribute_2: 'attribute_2',
      attribute_3: 'attribute_3',
   }
}

但这是我要反对的外观:

But this is what I want to object to obtain look like:

user {
   id: 1,
   name: "Name",
   attribute_1: 'attribute_1',
   attribute_2: 'attribute_2',
   attribute_3: 'attribute_3',
}

我想通过一个数据库调用来实现这一目标,而不是在调用之后设置属性.

I want to achieve this by a single database call instead of setting the properties after the call.

我发现这是一个非常有趣的话题,希望您能提供帮助!

I find this a very interesting topic, I hope you could help!

推荐答案

如果我的问题没对,您可以这样称呼:

If I got your problem right, you may call somthing like this:

DB::table('users')
    ->join('reviewer_attributes', 'users.id', '=', 'reviewer_attributes.user_id')
    ->find($id);

您可以添加 select 以获得每个表的特定属性:

you may add select to get specific attributes of each table:

DB::table('users')
    ->join('reviewer_attributes', 'users.id', '=', 'reviewer_attributes.user_id')
    ->select('users.id', 'users.name', 'reviewer_attributes.*')
    ->find($id);

更新:您还可以使用集合进行重组Eloquent返回的结果:

Update: You can also use collections to restructure your results returned by Eloquent:

$result = User::with('reviewerAttributes')->find($id);

$result = $result->get('reviewer_attributes')
                 ->merge($result->forget('reviewer_attributes')->all())
                 ->all();

这篇关于在Laravel 5中,如何从相关表中获取属性作为其自身表的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆