php - Laravel Eloquent 一對多的morph沒有值的問題
过去多啦不再A梦
过去多啦不再A梦 2017-05-27 17:43:22
0
1
645

現在有Topic, Post, Comment三個模型, Comment相對Topic和Post是一對多的關係, 也就是說每個Topic和Post都可以有多條Comment.
但現在嘗試插入Comment時, 發現並沒有插入對應的commentable_idcommentable_type#???
報錯如下:

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資料表中有$table->morphs('commentable');.

請問問題到底出在哪裡?`

过去多啦不再A梦
过去多啦不再A梦

全部回覆(1)
迷茫

comments 表中需要建立 commentable_idcommentable_type字段.如下图所示,其中, commentable_id 用于存放Topic或者Post的 id ,而 commentable_type 用來存放所屬模型的類別名稱。

你可以仔細看看laravel文件中的多態性關聯.

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!