Home > OS >  Is there a way to join table B to A in laravel but table B as array without duplicating rows from ta
Is there a way to join table B to A in laravel but table B as array without duplicating rows from ta

Time:08-24

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.

CodePudding user response:

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.

CodePudding user response:

If you have Phone and User models, these are the things you should do.

User.php (Model)

public function phones()
{
   return $this->hasMany(Phone::class, 'user_id', 'id');
}

-> The first parameter means the model to which the database we want to reach is connected.

-> The second parameter refers to the column that we will match in the database to which the model we specified in the first parameter is connected.

-> The third parameter specifies which column in the table our current model depends on will match with the column in our second parameter.

Controller:

public function list()
{
    $users = User::with('phones')->get();
}

Doing this will suffice.

  • Related