使用 laravel 的 eloquent 关系时出错

Error using laravel's eloquent relationships

我在尝试使用来自 eloquent 关系的数据时遇到问题。我在我的 post 模型中定义了一个关系。

class post extends Model
{
    //
    protected $fillable = ['title', 'contents', 'user_id', 'status'];

    public function users(){
        return $this->belongsTo('App\User');
    }

}

我正在尝试从我的控制器访问此关系,如下所示:

public function showBlog(){
        $post = post ::where('status', 1)
            ->users()
            ->orderBy('id', 'desc')
            ->paginate(3);
     return  view ('blog')
            ->with('posts', $post);
    }

但是我收到这个错误: 调用未定义的方法 Illuminate\Database\Query\Builder::users()

请问我该如何解决?我正在使用 laravel 5.3

因为关系是模型的行为,而您得到的是查询构建器实例,因为您只是在构建查询。该框架仍在构建查询,不确定它会从中准确获得的结果或模型,这是建立关系所必需的。

在访问关系之前,您需要先生成模型实例Post

这样试试:

post ::where('status', 1)->first()
            ->users()
            ->orderBy('id', 'desc')
            ->paginate(3);

这里的方法 first() 将首先 运行 查询 post ::where('status', 1) for Post 并为您获取第一个结果模型,然后执行其余查询在这个模型实例上。

但是,此查询只会为前 post 个结果的用户提供结果。如果你想获得所有 post 与用户关系尝试使用 with 像:

post::where('status', 1)->with('users')
            ->orderBy('id', 'desc')
            ->paginate(3); 

这将导致 posts 的分页结果有 users.

希望对您有所帮助。