doumie6223 2015-01-01 08:08
浏览 14
已采纳

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

I am cleaning up my code which I wrote as a hopeless noob.

I am creating a view with user statistics. My intention is to make a table showing both site and user stats, for instance:

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

I have several models such as Book, Quotation, Excerpt etc. To display the above, I define in my controller multipe variables

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

and then pass them this way

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

I have about 10 different models to serve - 20 variables. Is there a more elegant way to get the numbers and display them in view?

My own solution: create a two-dimensional array of values

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

and then I have only one variable to pass to my view. Is that elegant enough? Any better ideas?

  • 写回答

2条回答 默认 最新

  • duanpa5237 2015-01-01 08:44
    关注

    @lukasgeiter's answer is good, but I prefer another way which I'll add here as well.

    Personally, I would make a method to get the count either within the model or a repository. I'd go the other way around for the $userCountQuotes - that is, starting with the user rather than with the quotes - and I'd use the built-in functionality for it.

    Here's an example, which assumes that the models are properly related. In the User model:

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

    And in the Quote model:

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

    Then, in the view, pass the user and do this:

    Our repository has **{{ Quote::countAll() }}** quotes - **{{ $user->quotesCount() }}** of them are contributed by you.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳