Merhabalar,
Kullanıcıların girdiği postlar ve bunlara yapılan yorumlarla ilgili şemalarım şu şekilde:
user_posts
Schema::create('user_posts', function(Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('key', 16)->unique()->index();
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('user_post_id')->unsigned()->index()->nullable();
$table->foreign('user_post_id')->references('id')->on('user_posts')->onDelete('cascade');
$table->text('content');
$table->softDeletes();
$table->timestamps();
});
comments
Schema::create('comments', function(Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('type', 50)->index();
$table->text('detail');
$table->softDeletes();
$table->timestamps();
});
user_post_comments
Schema::create('user_post_comments', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('comment_id')->unsigned()->index();
$table->foreign('comment_id')->references('id')->on('comments')->onDelete('cascade');
$table->integer('user_post_id')->unsigned()->index();
$table->foreign('user_post_id')->references('id')->on('user_posts')->onDelete('cascade');
$table->integer('user_post_comment_id')->unsigned()->index()->nullable();
$table->foreign('user_post_comment_id')->references('id')->on('user_post_comments')->onDelete('cascade');
$table->softDeletes();
$table->timestamps();
});
UserPost modeli içerisinde yorum ilişkisini şu şekilde bağladım:
Comment.php
public function comments()
{
return $this->belongsToMany('\App\Comment', 'user_post_comments')->withTimestamps();
}
Comments isimli tabloya kaydedilen yorumu, ilgili posta şu şekilde iliştiriyorum:
$post = UserPost::findOrFail($id);
$comment = Comment::create([
'user_id' => user()->id,
'type' => 'post',
'detail' => $request->get('comment')
]);
$post->comments()->attach($comment);
Buraya kadar herşey tamam. Ama bu yorumlar direkt olarak gönderilmiş posta değil de, yapılan başka bir yoruma cevap olarak gönderilmiş olabilir. Bu sebeple şemada ayrıca user_post_comment_id isminde bir alan oluşturmuştum. Benim burada yapmak istediğim; attach metodu kullanırken, eğer yazılan yorum başka bir yoruma cevap niteliğinde ise, ilgili yorumun id'sini de attach metoduna iliştirmek. Bunu create metodu ile yapabileceğimi biliyorum, lakin bu durum için düşünülmüş başka bir çözümünüz varsa bilmek istiyorum.
Cevaplarınız için şimdiden teşekkürler.