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?`
迷茫2017-05-27 17:45:22
incomments
表中需要建立 commentable_id
和 commentable_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.