获取帖子字段以及每个帖子:最近评论的详细信息

问题描述 投票:0回答:1

使用Laravel(v6),希望收集带有last条注释的匹配帖子。或者,在我的情况下:匹配地点,并提供last访问的详细信息。

class Place extends Model
{
    public function visits(){
        return $this->hasMany(Timeline::class);
    }

    public function lastVisit(){
        return $this->visits()->orderBy('end', 'desc')->limit(1);
    }
...

此功能对单个地方有效:

Place::where('id',2)->withCount('visits')->with('lastVisit')->get()

但是对于多个地方,它仅显示last地方的lastVisit:

Place::where('name','like','%hotel%')->withCount('visits')->with('lastVisit')->get()

我也尝试过:

Place::where('name','like','%hotel%')
->withCount('visits')
->with(['visits' => function($e) {return $e->orderBy('end','desc')->first(); }])
->get()

这仅显示最后一个地方的最后一次访问,因此:总共仅一次访问。

[当我省略->first()时,每个地方确实包括全部对该地方的访问(按上次访问排序)

Place::where('name','like','%hotel%')
->withCount('visits')
->with(['visits' => function($e) {return $e->orderBy('end','desc'); }])
->get()

如何获得每个地方的最后一次访问?

laravel
1个回答
0
投票

使lastVisit关系具有一个:

public function lastVisit()
{
    return $this->hasOne(Timeline::class)->orderBy('end', 'desc');
}
© www.soinside.com 2019 - 2024. All rights reserved.