在我的 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对象中显示评级值?
答案 0 :(得分:1)
下面:
$article = Article::with('ratingAvg')->get();
你渴望加载这种关系:
public function ratingAvg()
所以你应该以这种方式访问视图中的关系:
@foreach ($article as $a)
<p>{{ $a->ratingAvg->rating }}</p>
@endforeach