Пытаюсь сделать вложенные комментарии.
Миграция:
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->text('description');
$table->unsignedBigInteger('parent_id')->nullable();
$table->foreignId('user_id')->nullable()->index()->constrained('users');
$table->foreignId('post_id')->nullable()->index()->constrained('posts');
$table->timestamps();
});
}
Модель Post
class Post extends Model
{
use HasFactory;
protected $table = 'posts';
protected $guarded = false;
public function category()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
public function getImageMainAttribute()
{
return url('storage/' . $this->main_image);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class)->whereNull('parent_id');
}
}
Модель Comment
class Comment extends Model
{
use HasFactory;
protected $table = 'comments';
protected $guarded = false;
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function post()
{
return $this->belongsTo(Post::class, 'post_id', 'id');
}
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
При таком запросе я получаю данные.
$post = Post::where('id', $id)->with([
'comments.user:id,name',
'comments.replies.user:id,name',
'comments.replies.replies.user:id,name',
'comments.replies.replies.replies.user:id,name',
])->get()->toArray();
Но работаю с ресурсами, и не могу понять как туда правильно передать данные. Я получаю только родительский комментарий, как тут к нему привязать ответы?
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
"id" => $this->id,
"title" => $this->title,
"description" => $this->description,
"main_image" => $this->imageMain,
"category" => $this->category,
"created_at" => Carbon::parse($this->created_at)->format(' F d, Y'),
"comments" => $this->comments,
];
}
}