【发布时间】:2015-06-03 08:03:54
【问题描述】:
我正在尝试使用Laravel 5 开发一个博客,我必须在帖子中与用户一起显示评论。
这是我的数据库表架构。
User
- 身份证
- 姓名
Posts
- 身份证
- post_content
- user_id
Comments
- 身份证
- 评论
- user_id
- post_id
这是我的User Model
public function posts()
{
return $this->hasMany('App\Models\Posts');
}
public function comments(){
return $this->hasManyThrough('App\Models\Comments','App\Models\Posts');
}
这是我的Posts Model
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function comments(){
return $this->hasMany('Ap\Models\Comments');
}
这是我的Comment Model
public function posts()
{
return $this->belongsTo('App\Models\Posts');
}
public function user(){
return $this->posts->name;
}
这是我如何访问user name的代码
$comments = Comments::find(1);
$comment['comment'] = $comments->comment;
$comment['user_name'] = $comments->name;
$comment['post_id'] = $comments->posts->id;
可能是我没有朝着正确的方向前进?如果我做得对,那么为什么它不起作用。
【问题讨论】:
-
您的模型在 App\Model 命名空间中吗?默认只是应用程序...
-
@Gregory 是的,我的模型在 App\Models 命名空间中,我刚刚修改了一点。
标签: php eloquent laravel-5 has-many-through