How does one get properties from related table as properties of it's own table in Laravel 5?

微笑、不失礼 提交于 2021-01-29 02:06:21

问题


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:

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).

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.

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.

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!


回答1:


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);

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);

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();



回答2:


You need export model to Json?
If so, override toArray method

public function toArray()
{
    $arr = parent::toArray();
    $reviewer_attributes = $this->getReviewerAttributesSomeHow();
    return array_merge($arr, $reviewer_attributes);
}


来源:https://stackoverflow.com/questions/37486342/how-does-one-get-properties-from-related-table-as-properties-of-its-own-table-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!