Laravel按计数返回UserTitle

时间:2019-06-13 05:41:08

标签: php laravel

在我的项目中,我希望通过标题表中的用户帖子,评论,问题和答案计数来生成用户标题。

我有标题表,可以添加新标题。每个标题都有自己的帖子数。因此,当用户拥有更多或相等的帖子数时,将从标题表生成标题。

问题是我无法通过用户发布数在titles表中获取更大的值。当我使用<=时会显示标题,但是当我使用>=时不会返回任何内容。

Ps:用户和标题表之间没有任何关系。它仅返回相等的标题数据。

我的代码如下:

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

我不知道为什么当计数大于或等于时不返回任何内容。

1 个答案:

答案 0 :(得分:0)

我将根据我的评论总结我的答案,并给出有关您的查询的提示。

基本上,代码中的条件与多个标题条目匹配。因此,选择第一个并不总是与正确的匹配。当您要匹配“最低”匹配标题时,您可能想要更改

$title = Title::where('postcount', '>=', $total)->first();

$title = Title::where('postcount', '>=', $total)->orderBy('postCount', 'ASC')->first();

其他一些增强建议

$commentcount = $this->hasMany('App\Comment')
                    ->whereUserId($this- >id)
                    ->count();

在您的(可能是User?)类中使用似乎很奇怪。您应该将其重构为类似

public function comments() 
{
    return $this->hasMany('App\Comment');
}

这定义了用户对其评论的理解。如果您现在想要在标题功能中包含大量用户评论,则只需执行

$this->comments()->count();

对所有3个关系进行此操作时,标题方法可能看起来像

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

这不仅使外观看起来更简洁-还可以帮助您将来处理这些关系时进行查询。