Laravel's eloquent relationship doesn't work much

I am making a kind of reddit site.

I have users, threadKarmas, table / model commentKarmas.

I want to get the user along with his karma number through streams and the comment that he 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');
}

There is no inverse relationship yet. I do not know how I will create it, but so far this does not work.

+4
source share
1 answer

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

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

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

+2
source

Source: https://habr.com/ru/post/1693080/


All Articles