Search code examples
laraveleloquentorm

Is there a way to join table B to A in laravel but table B as array without duplicating rows from table A please?


I have two tables:

Table A:

Users
id | Name
1 | Sam
2 | Tom

Table B:

Phones
id | Name | user_id
1 | Nokia | 1
2 | Samsung | 1
3 | Motorola | 1
4 | OnePlus | 2

When I joinLeft I have duplicate Users rows as:

Users.id | Users.Name | Phones.id | Phones.Name  | Phones.user_id
1 | Sam | 1 | Nokia | 1 | 
2 | Sam | 2 | Samsung | 1 | 
3 | Sam | 3 | Motorola | 1 | 
4 | Tom | 4 | OnePlus | 2 | 

How could I build the query, to have array instead duplicated Users rows please? Data is send as JSON.

I would expect data:

[
 {
   {
     Name: "Sam", 
     Phones: {
       Name: "Nokia",
     },{
       Name: "Samsung",
     },{
       Name: "Motorola",
     }
   },{
     Name: "Tom",
     Phones: {
       Name: "OnePlus",
     }
   }
]

Any help would be much appreciated. Thank you.


Solution

  • Laravel Eloquent way Run php artisan make:model Phones for phone model. you may have user model already if not do same for user php artisan make:model User

    now define relation insede User.php file

    use App/Model/Phone  //use Phone model
    
    public function phones(){
       return $this->hasMany(Phone::class);
    }
    

    now you can eggerload the relation like below:

    $user = User::with('phone')->get();
    

    and you can get: user_name = $user->name

    user_phones = $user->phone   // this will return  array of phones
    

    you can loop the phone insode foreach loop. Hope this will help.