简体   繁体   English

在Laravel5中使用雄辩模型获取表值

[英]Get Table values using Eloquent Model in Laravel5

I want to find username from post_id using Post_Tag table using Eloquent model. 我想使用Eloquent模型使用Post_Tag表从post_id中找到用户名。 Here are the tables. 这是表格。

User Table 用户表

user_id(pk)
username

Post Table 发布表

post_id(pk)
user_id(fk)

Post_Tag Table Post_Tag表

post_id(fk)
Tag_id(fk)

How can I fetch username from User table using Post_Tag table. 如何使用Post_Tag表从User表中获取用户名。 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. 先感谢您。

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? 您说一个Tag属于许多帖子,如何选择要获取用户名的众多帖子中的哪一个?

Do you want to get all the users who have a post with some PostTag? 您是否想让所有发布了带有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. 在artisan tinker或dd运行此结果,以便可以看到返回的结果,我认为这可以解决您的问题。 Just note that this may return a lot of data, you could use take instead of get to limit the results. 请注意,这可能会返回很多数据,您可以使用take而不是get来限制结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM