【发布时间】:2018-06-01 11:08:41
【问题描述】:
我有这些模型:
class Post extends Model
{
protected $primaryKey = 'post_id';
public function comments()
{
return $this->hasMany(Comment::class, 'post_id', 'post_id');
}
}
class Comment extends Model
{
protected $primaryKey = 'comment_id';
public function post()
{
return $this->belongsTo(Post::class, 'post_id');
}
}
class User extends Authenticatable
{
protected $primaryKey = 'user_id';
public function comments()
{
return $this->hasMany(Comment::class, 'user_id', 'commenter_id');
}
}
class MyController extends Controller
{
public function post($id = null)
{
$post = Post::where('post_id', $id)->first();
$comments = $post->comments;
}
}
我想要的是让每条评论的用户都像$post->comments->user 这样简单地获取用户信息,如下所示:
@foreach($post->comments as $comment)
{{ $comment->user->first_name.' '.$comment->user->last_name }}
@endforeach
我该怎么做?我想我需要一个名为 hasManyThrough 的东西,但它太复杂了,我很困惑:|
【问题讨论】: