在 Laravel5 中使用 Eloquent 模型获取 Table 值
Get Table values using Eloquent Model in Laravel5
我想从 post_id 使用 Post_Tag table 使用 Eloquent 模型查找用户名。这是 tables。
用户Table
user_id(pk)
username
Post Table
post_id(pk)
user_id(fk)
Post_Tag Table
post_id(fk)
Tag_id(fk)
如何使用 Post_Tag table 从用户 table 获取用户名。这是我尝试过的:
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();
一个标签属于多个 post,每个 post 将属于一个 owner/User。提前谢谢你。
如果你的关系正常,这样做就可以了:
PostTag::find(20)->post()->first()
->user()->first()->username;
你说一个Tag属于很多posts,那么在很多posts中你如何选择你想要获取用户用户名的哪一个?
是否要让所有拥有 post 的用户使用一些 PostTag?
编辑:试试这个:
PostTag::find(20)->with(['post', 'post.user'])->get();
运行 这在 artisan tinker 或 dd
结果中所以你可以看到什么是 returned,我认为这解决了你的问题。请注意,这可能 return 很多数据,您可以使用 take
而不是 get
来限制结果。
我想从 post_id 使用 Post_Tag table 使用 Eloquent 模型查找用户名。这是 tables。
用户Table
user_id(pk)
username
Post Table
post_id(pk)
user_id(fk)
Post_Tag Table
post_id(fk)
Tag_id(fk)
如何使用 Post_Tag table 从用户 table 获取用户名。这是我尝试过的:
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();
一个标签属于多个 post,每个 post 将属于一个 owner/User。提前谢谢你。
如果你的关系正常,这样做就可以了:
PostTag::find(20)->post()->first()
->user()->first()->username;
你说一个Tag属于很多posts,那么在很多posts中你如何选择你想要获取用户用户名的哪一个?
是否要让所有拥有 post 的用户使用一些 PostTag?
编辑:试试这个:
PostTag::find(20)->with(['post', 'post.user'])->get();
运行 这在 artisan tinker 或 dd
结果中所以你可以看到什么是 returned,我认为这解决了你的问题。请注意,这可能 return 很多数据,您可以使用 take
而不是 get
来限制结果。