我正在制作一种类似于 reddit 的网站。
我有用户、threadKarmas、commentKarmas 表/模型。
我想通过他创建的线程和评论检索用户以及他的业力数量。
$user = UserView::with([
'threadKarmaPoints',
'commentKarmaPoints'
])
->where('username', $username)
->firstOrFail();
用户关系:
public function threadKarmaPoints() {
return $this->hasManyThrough(
'App\Models\ThreadKarmaView',
'App\Models\ThreadView',
'userId',
'threadId',
'userId',
'threadId'
)->count();
}
public function commentKarmaPoints() {
return $this->hasManyThrough(
'App\Models\CommentKarmaView',
'App\Models\CommentView',
'userId',
'commentId',
'userId',
'commentId'
)->count();
}
public function user() {
return $this->belongsTo('App\Models\Views\UserView', 'userId');
}
还没有逆关系。我不知道我将如何创建它,但现在,它不起作用。
最佳答案
删除 ->count();
从关系定义和使用 withCount()
:
UserView::withCount(['threadKarmaPoints', 'commentKarmaPoints'])
->where('username', $username)
->firstOrFail();
如果还需要实际加载相关数据,添加
->with(['threadKarmaPoints', 'commentKarmaPoints'])
到查询。
关于Laravel Eloquent 关系有很多通过不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48584448/