dq1230123 2017-01-04 08:26
浏览 38

Laravel - 获取所有记录,而不仅仅是第一个?

today I am facing a problem with Laravel. What I want to do is get every 'stat' value for every record where government_type = higher_government. By the way, I am different types, but this is just one of many.

$higherGovernment = Cache::remember('government.higher_government', 1, function() {
    return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});

How can I get all the stats for all types instead of just calling ->first() ?

I have tried removing the ->first() but it doesn't do anything except give me this error:

Undefined property: Illuminate\Database\Eloquent\Builder::$stats

stats is a relationship by the way:

    public function stats(){
       return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
   }
  • 写回答

3条回答 默认 最新

  • douzao9845 2017-01-04 08:35
    关注

    If you only want one column from this table, you can use the select function to indicate wich ones you want.

    Like so:

    <?php
        $higherGovernment = Cache::remember('government.higher_government', 1, function() {
            return GovernmentRole::where('government_type', 'higher_government')->select('stats')->get();
        });
    

    The collection $higherGovernment will now contain GovernmentRole objects with one parameter, stats.

    If you would like this to be an array of only the stats property, you can use collections to pluck this value out of it. Like so:

    <?php
        $higherGovernment = Cache::remember('government.higher_government', 1, function() {
            return GovernmentRole::where('government_type', 'higher_government')->select('stats')->get()->pluck('stats');
        });
    

    Update:

    Now that we know that stats is a relation I think the best solution is to just load all GovernmentRole objects and eager load the relation. Then you can display the stats for every GovernmentRole.

    You can do it like this:

    <?php
        $higherGovernment = Cache::remember('government.higher_government', 1, function() {
            return GovernmentRole::where('government_type', 'higher_government')->with('stats')->get();
        });
    
        // Just an example on how to get the stats
        foreach ($g in $higherGovernment)
            echo $g->stats->count();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程