Reputation: 574
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
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