Eloquent return 关系数量和布尔值(如果用户也有关系)

Eloquent return amount of relation AND a bool if the user has the relation aswell

我有一个 "novels" 的模型,它是 "bookmarkable" 并且有 "bookmarks"

我想显示一本小说的书签数量,并确定当前登录的用户是否为该小说添加了书签。

App\Novel::withCount('chapters', 'bookmarks')
           ->with(['author', 'ratings'])
           ->newestPublished()
           ->paginate(10)

显示的这个调用工作得很好。但是,如果当前用户已将小说添加为书签,我很想直接看到结果。

为了计算书签的数量,我在我的小说模型中加入了以下内容

public function getBookmarksCountAttribute()
{
    return $this->bookmarks()->count();
}

我能否以某种方式创建另一种 "getBookmarksCountAttribute" 方法,然后像这样工作

public function getUserBookmarkCountAttribute()
{
    if ( !Auth::user() ) {
        return false;
    }

    return $this->bookmarks()->where('user_id', Auth::user()->id)->first() ? true : false;
}

有没有办法轻松地将其添加到我的查询中?

方法 first() 产生第一个结果或 null。

解决方案

public function getUserBookmarkCountAttribute()
{
    if ( !Auth::user() ) {
        return false;
    }

    return !is_null($this->bookmarks()->where('user_id', Auth::user()->id)->first());
}

备选方案

public function getUserBookmarkCountAttribute()
{
    if ( !Auth::user() ) {
        return false;
    }

    return $this->bookmarks()->where('user_id', Auth::user()->id)->first() instanceof Bookmark;
}

提示 1

您可以将属性添加到 $appends 数组,这样您就不需要将计数显式存储在 table 中。

提示 2

在您的模型中使用 Auth facade 不是一个好习惯。更好的方法是使用依赖注入将用户对象/id 传递给模型。