Reputation: 87
On my project I'm tying to generate user titles by users' post, comments, questions and answers count from titles table.
I have titles table which can I add new titles. And each title has own post count. So when a user has greater or equal post count title will be generated from titles table.
Problem is I can't fetch the greater value in the titles table with users post count. When I use <=
it shows the title but when I use >=
it doesn't return anything.
Ps: There aren't any relation between users and titles table. It returns only equal title data.
My codes are below:
public function title()
{
$commentcount = $this->hasMany('App\Comment')
->whereUserId($this- >id)
->count();
$questioncount = $this->hasMany('App\Question')
->whereUserId($this->id)
->count();
$answercount = $this->hasMany('App\Answer')
->whereUserId($this->id)
->count();
$total = $commentcount + $questioncount + $answercount;
$title = Title::where('postcount', '>=', $total)->first();
if ($title) {
$show = '<span class="badge badge-danger rutbe" style="background:' . $title->color . '">' . $title->text . '</span>';
return $show;
} else {
return false;
}
}
I can't figure out why doesn't return anything when greater or equal count.
Upvotes: 1
Views: 177
Reputation: 6812
I'll sum up my answer based on my comment and give the hints with regards to your queries.
Basically the where conditition in your codes matches multiple title entries. Therefore selecting the first will not always match the correct one. As you want to match the "lowest" matching title you probably want to change
$title = Title::where('postcount', '>=', $total)->first();
to
$title = Title::where('postcount', '>=', $total)->orderBy('postCount', 'ASC')->first();
Some other enhancement proposals
$commentcount = $this->hasMany('App\Comment')
->whereUserId($this- >id)
->count();
Seems to be weird to use in your (probably User?) class. You should refactor this to something like
public function comments()
{
return $this->hasMany('App\Comment');
}
This defines your users realtion to his comments. If you now want to have the amount of the users comments in your title function you can simply do
$this->comments()->count();
When doing this for all 3 of your relations your title method could look like
public function comments()
{
return $this->hasMany('App\Comment');
}
public function questions()
{
return $this->hasMany('App\Question');
}
public function answers()
{
return $this->hasMany('App\Answer');
}
public function title()
{
$total = $this->comments()->count() + $this->questions()->count() + $this->answers()->count();
$title = Title::where('postcount', '>=', $total)->orderBy('postcount', 'ASC')->first();
if ($title)
return '<span class="badge badge-danger rutbe" style="background:' . $title->color . '">' . $title->text . '</span>';
}
return false;
}
This does not only make it look & feel way cleaner - it also helps you with future queries where you handle these relations.
Upvotes: 1