Kenziiee Flavius
Kenziiee Flavius

Reputation: 1949

How to eloquent relationship with multiple results

Problem

I have two classes, Users & Posts. A user "hasMany" posts and a post "belongTo" a user. But when I call "User::all()" it doesn't automatically pull the users posts for obvious reasons, because if my user had relations to 100 different tables pulling all users would start to become pretty chunky.

Question

Is there a way to pull all users and all user->posts in one or few lines of code without going through a foreach loop?

I know i can use a mutator but the problem I have is my field is called user_id and i have tested it with this code:

public function getUserIdAttribute($id)
{
    return User::find($id);
}

But it will replace "user_id" field value with a user object, Id rather have it set to its own "temporary user" field within the result. I'm trying to find best practice!

Thank you in advance.

Upvotes: 2

Views: 183

Answers (1)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

What you're looking for is called Eager Loading

Inside your post model :

class Post extends Model
{

    protected $table='posts';
    public $primaryKey='id';

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

 }

now you want to get post with user use below code :

$posts=Post::with('user')->get();

inside your user model :

  class User extends Model
   {

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

  }

now you want to get a user with all posts :

$user=User::where('id',$id)->first();
$user_posts=$user->posts;

Upvotes: 1

Related Questions