Sounds like you want a join https://laravel.com/docs/9.x/queries#joins
Nov 21, 2022
10
Level 1
Implement `with` using query builder
I have tables with relationships like the following:
users:
id | name
1 | John
posts:
id | title | user_id
1 | Post 1 | 1
comments:
id | comment | user_id | post_id
1 | comment 1 | 1 | 1
I want to fetch the posts and comments related to a specific user using query builder without repeating the user data with every post, Just like how with works. So that posts would be an array:
DB::select("
SELECT id, name,
(SELECT id, title FROM posts WHERE user_id = 1),
(SELECT id, comment FROM comments WHERE user_id = 1)
FROM users
");
But this throws an error:
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
How to return posts as an array using query builder?
Please or to participate in this conversation.