Laravel eloquent selecting most recent row from joined table

前端 未结 2 738
我在风中等你
我在风中等你 2021-01-12 07:45

I have two tables, Project and Projectnote

There is a one to many relationship between project and projectnote.

I want to be able to list my projects and sel

2条回答
  •  执笔经年
    2021-01-12 08:19

    In your project model, make the notes relationship function look something like:

    public function notes() {
      return $this->hasMany('Note');
    }
    

    Then you can get the most recent Note of the Project with primary key 1 by chaining orderBy and first:

    Project::find(1)->notes()->orderBy('created_at', 'desc')->first();
    

    Also, is your note table called 'Note' or 'Notes'? (Keeping with Laravel style, it should be named singular as I have it in this code)

提交回复
热议问题