简体   繁体   中英

Best way for Retrieving data from more tables in Laravel

I am new to laravel and I have a simple question, I am writing the controllers for my application and i need to do one simple things, i have to return a model with data from more tables, how would you do this? for example: i need to return to the view a 'Comment' with the name of the 'User' that wrote the comment but the model 'Comment' has only the id of the 'User' in 'id_user', how do i return the comment with the name of the user?

You should use the relationship between comment and user models,

I suggest you learning relationship first (in your case every user can have many comments)

Then you can useOne To Many relationship

Then use 'With' and get every user with comments,

For instance :

$users = App\User::with('comment')->get();

foreach ($users as $user) {

   echo $user->comments->description;

}

Hope to help

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