Почтовая модель
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
public function users()
{
return $this->belongsTo('App\User');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
Модель комментария
class Comment extends Model
{
public function posts()
{
return $this->belongsTo('App\Post');
}
}
Модель тегов
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Tag');
}
Модель пользователя
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
Теперь мой вопрос заключается в том, как я могу получить доступ ко всем комментариям, которые принадлежат к сообщению с прокомментированным именем пользователя, и теги принадлежат этим сообщениям. Даже у меня есть путаница в отношении отношения тегов, потому что у него есть много-много отношения
спасибо
Модель тегов
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Tag');
// Should this be return $this->belongsToMany('App\Post');
}
Теперь решение по вашему вопросу - "EAGER LOADING", давайте посмотрим, как мы можем использовать его для вашей ситуации.
1. Все комментарии
$commentsCollection = Comment::all();
// this will give us all comments.
2. Сообщение с комментариями и пользователями и тегами
$postsCollection = Post::with('comments','users','tags')->get();
// this will give you collection of post with comments, users and tags.
//So here you have all tags that belongs the a particular post.
Отсутствует связь
У вас отсутствует связь между пользователями и комментариями.
Модифицированная модель комментариев
class Comment extends Model
{
public function posts()
{
return $this->belongsTo('App\Post');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Модифицированная модель USER
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
public function comments()
{
return $this->hasMany('App\Comment');
}