Jonathan Lightbringer
Jonathan Lightbringer

Reputation: 574

Laravel eloquent relationship has many through doesn't work

I'm making a sort of like reddit website.

I have users, threadKarmas, commentKarmas table/model.

I want to retrieve the user along with the number of his karmas through the threads and comment he has created.

$user = UserView::with([
            'threadKarmaPoints',
            'commentKarmaPoints'
            ])
            ->where('username', $username)
            ->firstOrFail();

User Relationships:

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');
}

No inverse relationship yet. I don't know how I will create it but for now, it doesn't work.

Upvotes: 4

Views: 277

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

Remove ->count(); from both relationship definitions and use withCount():

UserView::withCount(['threadKarmaPoints', 'commentKarmaPoints'])
    ->where('username', $username)
    ->firstOrFail();

If you also need to actually load related data, add ->with(['threadKarmaPoints', 'commentKarmaPoints']) to the query.

Upvotes: 2

Related Questions