search

Home  >  Q&A  >  body text

php - Laravel Eloquent one-to-many morph has no value problem

Now there are three models: Topic, Post, Comment. Comment has a one-to-many relationship with Topic and Post, that is to say, each Topic Both Post and Post can have multiple Comments.
But now when trying to insert Comment, I found thatthe corresponding commentable_id and commentable_type???# were not inserted. ##The error is reported as follows:

SQLSTATE[HY000]: General error: 1364 Field 'commentable_id' doesn't have a default value (SQL: insert into `comments` (`content`, `updated_at`, `created_at`)

App\Models\Comment

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

App\Models\Topic

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'commentable');
}

App\Models\Post

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'commentable');
}

Comments data table contains

$table->morphs('commentable');.

Excuse me, what is the problem?`

过去多啦不再A梦过去多啦不再A梦2745 days ago677

reply all(1)I'll reply

  • 迷茫

    迷茫2017-05-27 17:45:22

    incomments 表中需要建立 commentable_idcommentable_type字段.如下图所示,其中, commentable_id 用于存放Topic或者Post的 id ,而 commentable_type is used to store the class name of the model it belongs to.

    You can take a closer look at the polymorphic association in laravel documentation.

    reply
    0
  • Cancelreply