简体   繁体   中英

Laravel query latest record

I've this query:

I'm building a forum and I would like to show the latest message that has being posted. I'm doing that like this:

return Forum::with(['users' => function($query){
            $query->select('user.id', 'user.name', 'user.last_name')
}]);

forum model:

/**
 * @return mixed
 */
public function users()
{
    return $this->belongsToMany(User::class, 'message');
}

How do I only receive the latest user. Right now I receive them all.

Thanks a lot!

public function users()
{
    return $this->belongsToMany(User::class, 'message')->orderBy('id', 'desc');
}

If you want to limit the number of users returned, append ->take(10); to take only last 10 users

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM