1

在我的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"}}

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

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 对象的评分值?

4

1 回答 1

1

这里:

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

您正在急切地加载此关系:

public function ratingAvg()

因此,您应该以这种方式访问​​视图中的关系:

@foreach ($article as $a)
    <p>{{ $a->ratingAvg->rating }}</p>
@endforeach
于 2015-12-12T14:18:36.390 回答