我猜它是一个模型关系错误,但我似乎无法确定它。
我有4张桌子
users: id, name, email...
subreddits: id, user_id...
posts: id, title, subreddit_id, user_id...
moderators: id, user_id, subreddit_id...
我正试图通过热切加载' user.votes'来获取所有帖子。和' subreddit.moderators'
$post = Post::with('user.votes')->with('subreddit.moderators')->findOrFail($post->id);
但我一直收到这个错误
Connection.php第636行中的QueryException:
SQLSTATE [42S22]:未找到列:1054未知列' users.moderators'在' where子句' (SQL:从
users
中选择*users
。{17}中的moderators
)
如果我单独使用subreddit
加载它,它会起作用,但我也需要获得subreddit的版主。
编辑:我从moderators
模型中的moderators()
方法中删除了Subreddit
字段,并将App\User
替换为App\Moderator
,我现在可以获得subreddit问题及其主持人。但是,访问$post->subreddit->moderators->user_id
会向我显示此错误Undefined property: Illuminate\Database\Eloquent\Collection::$user_id
这些是我的模特
User
模型
public function subreddit() {
return $this->hasMany('App\Subreddit');
}
public function posts() {
return $this->hasMany('App\Post');
}
public function votes(){
return $this->hasManyThrough('App\Vote','App\Post');
}
public function moderators(){
return $this->hasManyThrough('App\Moderator', 'App\Subreddit');
}
Subreddit
模型
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->hasMany('App\Post');
}
public function moderators() {
return $this->hasMany('App\User', 'moderators');
}
Post
模型
public function user() {
return $this->belongsTo('App\User');
}
Moderator
模型
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->belongsTo('App\Post');
}
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
public function votes() {
return $this->hasMany('App\Vote');
}
public function moderators() {
return $this->hasMany('App\Moderator');
}
Vote
模型
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->belongsTo('App\Post');
}
AuthServiceProvider
$gate->define('update-post', function ($user, $post, $isModerator) {
// Check if user is subreddit owner
if ($user->id === $post->subreddit->user->id) {
return true;
}
// Check if user is the post author
if ($user->id === $post->user_id) {
return true;
}
// Check if user is a moderator of a subreddit
if ($isModerator) {
return true;
}
return false;
});
答案 0 :(得分:2)
如果您想要所有版主的用户ID集合,请使用:
$ids = Post::findOrFail($id)->subreddit->moderators()->lists('user_id');
如果您想检查给定用户是否是subreddit上的主持人,请使用以下命令:
$subreddit = Post::findOrFail($id)->subreddit;
$isModerator = $subreddit->moderators()->where('user_id', $user->id)->exists();