简体   繁体   中英

Display all Posts from all Users

For example we have two tables

User and Post

User has many posts, but Post belongs to one User.

I want to display all the posts from the users on one page.

For example: posts table

So how can I display multiple posts from ALL the users on one page?

First: To get all users in you controller

$users = User::All();

then you can pass this $users to your view and loop through all the $users

foreach($users as $user){
   echo $user_email = $user->email;
   $user_posts = $user->post; //multiple posts, but need to establish relation
   echo "posts for this user";
   foreach($user_posts as $p){
       echo $p->title;
   }
}

Note: For big data it can be slower and not good practice.

User model for users table: should have onetoMany relationship with post as

...........
...........
public function posts(){
    return $this->hasMany('App\Post','user_id');
}
..........
..........

Post model for posts table

........
........
public function  user(){
    return $this->belongsTo('App\User');
}
.........
.........

You need to put user_id field in you posts table.
Please also see about lazy loading and Eager Loading

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