计算多个模型并将变量带到视图的优雅方式 - Laravel


elegant way to count multiple models and carry variables to a view - laravel

我正在清理我作为一个绝望的菜鸟写的代码。

我正在创建一个包含用户统计信息的视图。我的目的是制作一个显示网站和用户统计信息的表格,例如:

Our repository has **1000** quotes **120** of them are contributed by you.

我有几个模型,如书籍,报价,摘录等。为了显示上述内容,我在控制器中定义了多个变量

$userCountQuotes = count(Quote::where('creator_id','=',$userid)->get());
$CountQuotes = count(Quote::get());

然后以这种方式传递它们

return View::make('userworkspace.stats', compact('userCountQuotes','CountQuotes'))

我有大约 10 个不同的模型要服务 - 20 个变量。有没有更优雅的方式来获取数字并将它们显示在视图中?

我自己的解决方案:创建一个二维值数组

$stats= array
(
array("Books",22,18),
array("Quotes",15,13)
...
);

然后我只有一个变量要传递给我的视图。这够优雅吗?有什么更好的主意吗?

首先,与其检索结果(get()),然后使用count(),不如使用count()方法,该方法将使用底层的SQL计数

$userCountQuotes = Quote::where('creator_id', '=', $userid)->count();
$CountQuotes = Quote::count();

现在要将其传递给视图 id,请使用一个结构不同的数组:

$stats = array
(
    'Books' => array(
        'total' => 22,
        'user' => 18
    ),
    'Quotes' => array(
        'total' => 15,
        'user' => 13
    )
)

这就是你的观点,然后是什么样的

@foreach($stats as $type => $values)
    Our repository has {{ $values['total'] }} {{ $type }} {{ $values['user'] }} of them are contributed by you.
@endforeach

@lukasgeiter的答案很好,但我更喜欢另一种方式,我也会在这里添加。

就个人而言,我会制作一种方法来获取模型或存储库中的计数。对于$userCountQuotes,我会采取相反的方式 - 也就是说,从用户而不是引号开始 - 我会使用它的内置功能。

下面是一个示例,它假定模型正确相关。在用户模型中:

public function quotesCount()
{
    return $this->quotes()->count();
}

在报价模型中:

public static function countAll()
{
    return static::all()->count();
}

然后,在视图中,传递用户并执行以下操作:

Our repository has **{{ Quote::countAll() }}** quotes - **{{ $user->quotesCount() }}** of them are contributed by you.