Chopra
Chopra

Reputation: 571

Get Table values using Eloquent Model in Laravel5

I want to find username from post_id using Post_Tag table using Eloquent model. Here are the tables.

User Table

user_id(pk)
username

Post Table

post_id(pk)
user_id(fk)

Post_Tag Table

post_id(fk)
Tag_id(fk)

How can I fetch username from User table using Post_Tag table. Here is what I have tried:

class Post extends Eloquent {

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

class PostTag extends Eloquent {

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


$posts = PostTag::with('post')->where('tag_id','=','20')->get();

One tag belongs to Multiple posts and each post will belong to an owner/User. Thank you in advance.

Upvotes: 1

Views: 261

Answers (1)

hfingler
hfingler

Reputation: 2014

If your relations are working this would do it:

PostTag::find(20)->post()->first()
                 ->user()->first()->username;

You say one Tag belongs to many posts, how do you choose which of the many posts you want to get the user's username?

Do you want to get all the users who have a post with some PostTag?

Edit: Try this:

PostTag::find(20)->with(['post', 'post.user'])->get();

Run this in artisan tinker or dd the result so you can see what is returned, I think this solves your problem. Just note that this may return a lot of data, you could use take instead of get to limit the results.

Upvotes: 1

Related Questions