简体   繁体   中英

how to access the one to many model relation in laravel,with access all the columns

I am creating a comment table in my Laravel project so that users can comment on products. I want to make a table which can integrate with my user table (like a one-to-many relationship) in Laravel.

Here is my code:

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

Here I send my data to the view in my project. I don't understand how to access the data which is in my user table along with the data in the comment table.

First comments::orderBy... should be Comments::orderBy... ,
But you don't need that, It's so simple to get user comments :

First Method: Using with()

Once the relationship has been defined, we can access the collection of comments by accessing the comments property. Remember, since Eloquent provides "dynamic properties", we can access relationship methods as if they were defined as properties on the model:

$books = App\Book::with('author')->get();

foreach ($books as $book) {
  echo $book->author->name;
}

Second Method : Direct

Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with method:

$comments = App\Post::find(1)->comments;

foreach ($comments as $comment) {
  //
}
In your case :
 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 ]); }

Hope it helps;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM