phplaraveldatabaselaravel-5relational-database

How does one get properties from related table as properties of it's own table in 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:

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!


Solution

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