php - Laravel Eloquent one-to-many morph has no value problem
过去多啦不再A梦
过去多啦不再A梦 2017-05-27 17:43:22
0
1
675

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梦

reply all(1)
迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template