如何在laravel中访问一对多模型关系,并访问所有列

时间:2020-03-27 18:07:53

标签: php sql laravel

我正在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
        ]);
    }

在这里,我将数据发送到项目中的视图。我不明白如何访问用户表中的数据以及注释表中的数据。

1 个答案:

答案 0 :(得分:0)

第一个comments::orderBy...应该是Comments::orderBy...
但是你不需要那个 获得用户评论非常简单:

第一种方法:使用with()

一旦定义了关系,我们就可以通过访问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
    ]);
}

希望有帮助;)