1

I'm trying to load last 5 comments with related posts selecting only id and title from post.

In first case I decided get all columns from posts:

Comment::with(['post'])->take(5)->orderBy('id', 'desc')->get();

And it's working fine.

But when I try get only two columns ("id, title") then nothing from posts is loaded.

Comment::with(['post:id,title'])->take($number)->orderBy('id', 'desc')->get();

I did a test and when I removed "orderBy('id', 'desc')" then was fine again.

Comment::with(['post:id,title'])->take($number)->get();

So must be some problem with "orderBy" option.

Is it any way to fix it? It's mean get only selected columns from "posts" table and order results from the last one?

Thank you.

3
  • You need to clarify by what id you want to order. id of post or id of comment. Commented May 27, 2018 at 17:14
  • Why not getting the post by id and then getting all comments for it? Commented May 27, 2018 at 17:17
  • @MaihanNijat because task is to get last comments Commented May 27, 2018 at 17:18

1 Answer 1

2

As both your Comment and Post models contain id, Laravel doesn't know by which one do you want to sort. So, add a table name to your orderBy:

Comment::with(['post:id,title'])->take($number)->orderBy('comments.id', 'desc')->get();

Here comments is name of your table/entity, maybe it is comment.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Now it is obvious for me :D.

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.