Laravel检索对象中的数据对象

时间:2015-12-12 13:22:43

标签: php json laravel laravel-5 laravel-blade

在我的 ArticleController 中,我有:

public function index()
    {
        $article= Article::with('ratingAvg')->get();        
        return view('article.index',['article' => $article]);
    }

在我的文章模型中:

public function ratingAvg()
    {
      return $this->hasOne('App\Rating', 'article_id')
        ->selectRaw('article_id AVG(rating) as rating')
        ->groupBy('article_id');
    }

article.index

@foreach ($article as $a)
  <p>{{$a}}</p>
@endforeach

因此,我从数据库收到以下数据:

{"id":10,"name":"Article1","rating_avg":{"article_id":10,"rating":"4.0"}}

ArticleController 中运行dd($article);时,我会收到:

Collection {#194 ▼
  #items: array:2 [▼
    0 => Article{#188 ▼
      #table: "articles"
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:12 [▶]
      #original: array:12 [▶]
      #relations: array:1 [▼
        "ratingAvg" => Rating {#195 ▼
          #table: "ratings"
          #connection: null
          #primaryKey: "id"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:2 [▼
            "article_id" => 10
            "rating" => "4.0"
          ]
        }
      ]
    }
  ]
}

我的问题是,如何在rating_avg对象中显示评级值?

1 个答案:

答案 0 :(得分:1)

下面:

$article = Article::with('ratingAvg')->get(); 

你渴望加载这种关系:

public function ratingAvg()

所以你应该以这种方式访问​​视图中的关系:

@foreach ($article as $a)
    <p>{{ $a->ratingAvg->rating }}</p>
@endforeach