1

I'm new to Laravel, let me straight forward to the question.

Suppose I have 'Posts' table and 'Comments' table

And the first 'Post' has 3 comments,

What is the best query method to achieve this kind of result

Post => (
   [0]=> array (
      [id]=>1
      [content]=> This is my first Post!
      [comments]=> array(
         [0]=>array(
            [id]=>1
            [post_id]=>1
            [content]=> First comment!
         )

         [1]=>array(
            [id]=>2
            [post_id]=>1
            [content]=> Second comment!
         )

         [2]=>array(
            [id]=>3
            [post_id]=>1
            [content]=> Third comment!
         )


      )
   )
)

2 Answers 2

1

Eager load the relationship:

$posts = Post::with('comments')->get()->toArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Mazenin : please help :(
@Angger you need to define hasMany() relationship first to make it work.
0

You can use Eloquent relationships. https://laravel.com/docs/5.4/eloquent-relationships#one-to-many.

The example is exactly what you're looking for! (:

1 Comment

No, It only return comments values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.