Laravel Eloquent 关系有很多通过不起作用

标签 laravel eloquent

我正在制作一种类似于 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/

相关文章:

php - 为什么 with resource 没有在 Laravel 中执行

javascript - Laravel 和 Ajax 如何处理接收到的数据并将其保存在数据库中?

php - 如何更新记录 'pay' laravel?

php - laravel eloquent 中的 mysql LIKE 条件

php - Laravel:查找是否存在数据透视表记录

mysql - Laravel Eloquent : order results by field in related table

php - 添加第二个操作或链接到 Laravel 通知

php - 在 mysql 中更新日期和时间时如何修复 laravel 的错误日期和时间

php - 检查模型 C 是否与任何与模型 A 相关的模型 B 相关

php - 我想将 SQL 查询转换为 Laravel Eloquent