Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

damian0021's avatar

Get last post with relation (3 tables)

Hi, I'm having trouble connecting my relationship in Eloquence.

I have 3 models:

  • Category
  • Thread
  • Post I want to display the newest post in the category.

Model Category:

public function lastPostIndex()
    {
        return $this->hasOne(Post::class, 'thread_id')->latestOfMany();                
    }

Model Post:

public function lastPostIndex()
    {
        return $this->belongsTo(Thread::class, 'thread_id');                 
    } 

Controller:

$categories = Category::with('lastPostIndex.lastPostIndex')->get();

The data is downloading, however, these are not the last posts created.

0 likes
4 replies
SilenceBringer's avatar

@damian0021 maybe because here

return $this->hasOne(Post::class, 'thread_id')->latestOfMany();     

you join the posts table by thread_id field instead of id of posts table? I think it should be

return $this->hasOne(Post::class)->latestOfMany(); 

(assuming you follow naming conventions)

damian0021's avatar

Hi @silencebringer,

unfortunately example ten does not work.

For you to be more aware, I have the following loudspeakers in the models:

  • Category - ID
  • Thread - ID, category_ID
  • Post - id, thread_id
SilenceBringer's avatar

@damian0021 you have capitalized ID in thread? this way

return $this->hasOne(Post::class, 'thread_id', 'ID')->latestOfMany(); 
damian0021's avatar

@silencebringer,

When he gives:

return $this->hasOne(Post::class, 'thread_id', 'ID')->latestOfMany(); 

Did not work.

When I change to:

return $this->hasOne(Post::class, 'thread_id', 'id')->latestOfMany(); 

It works, but it does not search for my recently written post by searching threads in a given category.

When I present in the Category model:

return $this->hasOne(Post::class)->latestOfMany();

Receives a message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.category_id' in 'field list' (SQL: select `posts`.* from `posts` inner join (select MAX(`posts`.`id`) as `id_aggregate`, `posts`.`category_id` from `posts` where `posts`.`category_id` in (1, 2) group by `posts`.`category_id`) as `latestOfMany` on `latestOfMany`.`id_aggregate` = `posts`.`id` and `latestOfMany`.`category_id` = `posts`.`category_id`)

May you understand what he wants to delay. I have 3 models:

  • category - id,
  • thread - id, categories_id
  • post - id, thread_id

In the category - he wants to take out the last post that was written and connect it with a relationship with the thread.

Please or to participate in this conversation.