【问题标题】:how to access the one to many model relation in laravel,with access all the columns如何访问laravel中的一对多模型关系,并访问所有列
【发布时间】:2020-07-08 12:47:56
【问题描述】:

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

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

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    第一个 comments::orderBy... 应该是 Comments::orderBy... ,
    但你不需要那个, 获取用户cmets就是这么简单:

    第一种方法:使用 with()

    一旦定义了关系,我们就可以通过访问 cmets 属性来访问 cmets 的集合。请记住,由于 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
        ]);
    }
    

    希望对你有帮助;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多