1
votes

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.

1
You need to clarify by what id you want to order. id of post or id of comment.u_mulder
Why not getting the post by id and then getting all comments for it?Maihan Nijat
@MaihanNijat because task is to get last commentsu_mulder

1 Answers

2
votes

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.