Mostafa Norzade
Mostafa Norzade

Reputation: 1766

laravel join two table and foreach on result

I use join in laravel for two tables (DB is a secondary database. I do not have a model for these tables):

$users = DB::connection('mysql2')
                       ->table('users')
                       ->join('usermeta', 'users.id', 'usermeta.user_id')
                       ->select('users.*', 'usermeta.*')
                       ->get();

This is the result of a query:

{
  +"id": 1
  +"user_email": "[email protected]"
  +"umeta_id": 502
  +"user_id": 1
  +"meta_key": "first_name"
  +"meta_value": "xxxx"
},
{
  +"id": 1
  +"user_email": "[email protected]"
  +"umeta_id": 503
  +"user_id": 1
  +"meta_key": "last_name"
  +"meta_value": "yyyy"
},
{
  +"id": 2
  +"user_email": "[email protected]"
  +"umeta_id": 504
  +"user_id": 2
  +"meta_key": "first_name"
  +"meta_value": "xxxxx"
},
{
  +"id": 2
  +"user_email": "[email protected]"
  +"umeta_id": 505
  +"user_id": 2
  +"meta_key": "last_name"
  +"meta_value": "yyyy"
},

how to add foreach on users and show a list of users (with first name and last name)?

Upvotes: 0

Views: 780

Answers (1)

Moussab Kbeisy
Moussab Kbeisy

Reputation: 606

there is a way to achieve this by optemizing mysql query .
this is my answere using php :

    $check_array = [];
       $output=[];
       foreach ($users as $user){
           if (!in_array($user['user_id'],$check_array)){
               $output[$user['user_id']]['user_id'] = $user['user_id'];
               $output[$user['user_id']]['user_email'] = $user['user_email'];
               $output[$user['user_id']][$user['meta_key']]=$user['meta_value'];
           }else{
               $output[$user['user_id']][$user['meta_key']]=$user['meta_value'];
           }
       }
       dd($output);

the output will look like this :

array:2 [▼
  1 => array:4 [▼
    "user_id" => 1
    "user_email" => "[email protected]"
    "first_name" => "xxxx"
    "last_name" => "yyyy"
  ]
  2 => array:4 [▼
    "user_id" => 2
    "user_email" => "[email protected]"
    "first_name" => "xxxx"
    "last_name" => "yyyy"
  ]
]

then you can easily display the output .

Upvotes: 2

Related Questions