我正在Laravel项目中创建评论表,以便用户可以对产品发表评论。我想在Laravel中创建一个可以与用户表集成的表(例如一对多关系)。
这是我的代码:
public function buyproduct($id){
$user = Auth::user();
$users_comment = User::with('comments')->get();
$comments =comments::orderBy('id','desc')->get();
$renimage = Clothes::where('id',$id)->first();
return view('pages.products',[
'renimage'=>$renimage,
'google_avater'=>$user,
'comments'=>$users_comment
]);
}
在这里,我将数据发送到项目中的视图。我不明白如何访问用户表中的数据以及注释表中的数据。
答案 0 :(得分:0)
第一个comments::orderBy...
应该是Comments::orderBy...
,
但是你不需要那个
获得用户评论非常简单:
一旦定义了关系,我们就可以通过访问comments属性来访问评论集合。请记住,由于Eloquent提供了“动态属性”,因此我们可以访问关系方法,就像它们被定义为模型的属性一样:
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
非常感谢,我们可以使用紧急加载将此操作减少为仅2个查询。查询时,可以使用with方法指定要急切加载的关系:
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
//
}
在您的情况下:
public function buyproduct($id){
$user = Auth::user();
$users_comment = User::with('comments')->get();
//blow line changed
$comments =$users_comment->comments;
$renimage = Clothes::where('id',$id)->first();
return view('pages.products',[
'renimage'=>$renimage,
'google_avater'=>$user,
'comments'=>$users_comment
]);
}
希望有帮助;)