Home > front end >  eloquent column selection from both tables (Primary & Foreign)
eloquent column selection from both tables (Primary & Foreign)

Time:04-14

I have two tables, User and Post. One User can have many posts and one post belongs to only one user.

In my User model I have a hasMany relation...

public function post(){
    return $this->hasmany('post');
}

And in my post model I have a belongsTo relation...

public function user(){
    return $this->belongsTo('user');
}

Now I want to join these two tables using Eloquent with() but want specific columns from the first and second table. I know I can use the Query Builder but I don't want to.

When in the Post model I write...

public function getAllPosts() {
    return Post::with('user')->get();
}

It runs the following queries...

select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)

But what I want is...

select `id`, `text AS post_text` from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)

When I use...

Post::select('id', 'text AS post_text')->with('user:id, username')->get();

It returns user null.

{
    "id": "1",
    "post_text": "text",
    "user": null
}

CodePudding user response:

Just change the code to

public function getAllPosts() {
    return Post::with('users:id,username')->get('id', 'text AS post_text');
}

CodePudding user response:

There is a problem in the next line:

Post::select('id', 'text AS post_text')->with('user:id, username')->get();

In the select it expects an array

Post::select(['id', 'text AS post_text'])->with('user.id, username')->get();
  • Related