I have problem with reference slug on my table comment. i want to add slug post from table posts.

so when i insert comment, it can put commentable_slug from post table. Here are my comment table and post table. commentable_id = 32, it's mean post_id and you can see slug from post, that is (quia-pariatur-expedita-vel-quia)

comment table enter image description here

post table enter image description here

and my migration

Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('parent_id')->unsigned()->nullable();
        $table->text('body');
        $table->integer('commentable_id')->unsigned();
        $table->foreign('commentable_id')->references('id')->on('posts')->onDelete('cascade');
        $table->string('commentable_slug')->nullable();
        $table->foreign('commentable_slug')->references('slug')->on('posts')->onDelete('cascade');
        $table->string('commentable_type');
        $table->timestamps();
    });

i use null in commentable_slug because it's always warn me Cannot add or update a child row: a foreign key constraint fails.

when i was tried that my field commentable is null.

my comment model and relation

 class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(Member::class);
    }
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

and my post model

    class Post extends Model
    {
     public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function comments()
        {
            return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
        }
    }

where part of code is wrong? the expected result must be: enter image description here

how to solve my problem ?

1 Answers

1
Community On Best Solutions

Ok I think I understand what you are trying to do. The problem is here

public function post()
{
    return $this->belongsTo(Post::class);
}

Because its a polymorphic relationship you cant use a standard belongsTo as you don't have a post_id in your table.

You need to use a morphTo function like this in your comment model

public function commentable()
{
    return $this->morphTo();
}

So when you call

$comment->commentable()->get();

It will then return whatever polymorphic model is linked.

Bit hard to give a precise code example as you haven't really given any use case.

But as said in the comments you should not need to link both id and slug. Also I believe MySQL has issues when using text fields for keys and I think you need to specify a field length, but not 100% on that, maybe someone who knows more about MySQL could confirm that.