How to attach values from an array to another key in another array

Viewed 41

I'm using laravel query-builder to get data from database but what I need is just based on php.

Here's some code:

$data = DB::select('SELECT * FROM news ORDER BY created_at DESC'):
foreach ($data as $rows) {
    $teacher = DB::select('SELECT name FROM teachers WHERE id = ?', [$row->teacher_id]);
    $data->teacher = $teacher; 
}
return $data;

The $data variable has the following array:

array:4[
    0 => {
        "id":3
        "teacher_id": 2
    }
    1 => {...some similar keyvalue pairs}
    2 => { ...another key-value pairs}
]

So the question is that I want the teacher name from the database to be attached to each $data array iteration by using the id from each $data iteration to get the teacher name from the second query.

Does anyone get this?

1 Answers

You can solve this issu using a single query ..

SELECT news.*, teachers.name 
FROM news
INNER JOIN  teachers where teachers.id = news.teacher_id
ORDER BY created_at DESC
Related