I'm trying to return a blog_post,blog_title from a MYSQL databse but I also need the user and his/her's data (in seperate array's)
The output should be like
array(
'blog1' => array(
'title' => 'this is a title',
'post' => 'This is the blogs content',
'user' => array(
'username' => 'Name',
'lastname' > 'Lastname'
)
),
'blog2' => array(
'title' => 'this is a title',
'post' => 'This is the blogs content',
'user' => array(
'username' => 'Name',
'lastname' > 'Lastname'
)
)
)
Using mysql there is no way of doing this in one query because it will mix up the two tables.
I have tried using left_join,right_join and selecting from multiple tables like
SELECT * FROM blogs a, users b WHERE b.id = a.id
Then I have tried using a foreach and a while loop.
$posts = array();
$x = 0;
while(++$x < 20){
$post = DB::query('SELECT * FROM posts WHERE id = '.$id.' ');
$post['user'] = DB::query('SELECT * FROM users WHERE id = '.$post['user_id'].' ');
$posts[] = $post;
}
But this will always return the same post/user
If you need a posts for a particular user it is possible to do like this (assumed you have a relation in posts table to users table by foreign key fk_user for each post):
$user_id = 1;
$posts = DB::query(
'SELECT posts.*,
users.username,
users.lastname
FROM posts
JOIN users ON users.id = posts.fk_user
WHERE user.id = '.$user_id
);
In case you need just a list of posts with related user info you can act as follows:
$posts = DB::query(
'SELECT posts.*, users.username, users.lastname
FROM posts
JOIN users ON users.id = posts.fk_user
LIMIT 100'
); // use your limit here
After you have a $posts array filled you can iterate and rearrange (if you need) or just use it as is:
foreach( $posts as $post ) {
// print post info here or rearrange array
$post['user'] = [
'username' => $post['username'],
'lastname' => $post['lastname'],
];
}