php - Laravel 模型返回空关系?

标签 php laravel eloquent

我正在为照片帖子编写一个网站,并且我有这些与喜欢相关的功能(它们确定用户是否喜欢特定的帖子)

后模型:

public function likes()
{
    return $this->hasMany('Like');
}

public function isLiked()
{
    return $this->likes()->where('user_id', Auth::user()->id);
}

例如后 Controller 函数:

public function postsByType($type)
{
    if($this->user){
        $posts = Post::with('isLiked')->where('type', '=', $type)->paginate(12);
    } else {
        $posts = Post::where('type', '=', $type)->paginate(12);
    }
    return $posts;
}

当用户未登录时,不运行查询,有什么方法可以在 MODEL 函数中返回 null

我想避免在后 Controller 中写if

我考虑过以下解决方案,但它不起作用...

public function isFollowing()
{
    return $this->setRelation('isFollowing', null);

}

出现这个错误: 调用未定义的方法 Illuminate\Database\Query\Builder::addEagerConstraints()

最佳答案

因为你可能总是想获取关系(除非没有用户登录)我建议你在你的模型中做这样的事情:
(我还将关系重命名为 liked,稍后您会看到原因)

public function newQuery(){
    $query = parent::newQuery();
    if(Auth::check()){
        $query->with('liked');
    }
    return $query;
}

现在每次使用模型运行查询时,如果用户已登录,将添加 with('isLiked')

不过还有一个问题。如果您访问 isLiked,查询将无论如何运行。甚至对于每个帖子,因为它不是急于加载的。您可以通过添加属性访问器来解决这个问题:

public function getIsLikedAttribute(){
    if(Auth::guest) return false;
    return ! $this->liked->isEmpty();
}

所以在你看来你可以这样做:

@if($post->isLiked)

注意:将 newQuery() 中的内容移动到全局范围会更好。请务必在 the documentation 中查看如何执行此操作如果你有兴趣。

这是一个范围示例。创建一个类,我们称它为 LikedScope:

class LikedScope implements Illuminate\Database\Eloquent\ScopeInterface {
    public function apply(Builder $builder, Model $model){
        if(Auth::check()){
            $builder->with('liked');
        }
    }

    public function remove(Builder $builder, Model $model){

    }
}

然后将其添加到您的模型中:

public static function boot(){
    parent::boot();
    static::addGlobalScope(new LikedScope);
}

关于php - Laravel 模型返回空关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570318/

相关文章:

php - where_in 只返回 1 行

javascript - JQuery Post 错误 react

php - MySQL 的编码问题

laravel - 两个 store() 方法,其中一个不起作用(调用未定义的方法 save())

php - MySQL在多个表中搜索

php - 如何使用 Laravel 和 Eloquent 查询具有多种关系的数据透视表

php - PHP:创建可扩展的CMS系统

php - 如何使用 linux 的 shell 脚本运行 Laravel 路由?

php - 如何在数组的集合上实现子集合?

php - 检查日期是否在 Laravel 5 的日期范围内