代码之家  ›  专栏  ›  技术社区  ›  Akshay Khale

拉威尔:雄辩模型中的多重多态关系

  •  0
  • Akshay Khale  · 技术社区  · 8 年前

    我有一个名为Comments的表,其结构如下

    Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
    $table->morphs('commentable');
    $table->morphs('creatable');
    $table->text('comment');
    $table->timestamps();
    });
    

    class Comment extends Model
    {
        public $fillable = ['comment'];
    
        public function commentable()
        {
            return $this->morphTo();
        }
    
        public function creatable()
        {
            return $this->morphTo();
        }
    }
    

    我有两种多态关系

    commentable

    creatable

    如何对用户创建的帖子添加评论?

    public function addComment($creatable, $comment)
    {
            $this->comments()->create(['comment' => $comment, 'creatable' => $creatable]);
    }
    

    它确实工作,我收到以下错误

    Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'creatable_type' doesn't have a default value (SQL: insert into `post_comments` (`comment`, `commentable_id`, `commentable_type`, `updated_at`, `created_at`) values (Test Comment, 1, App/Post, 2018-08-31 10:29:14, 2018-08-31 10:29:14))'
    

    提前谢谢!!!

    1 回复  |  直到 8 年前
        1
  •  5
  •   Jonas Staudenmeir    8 年前

    你可以用 make() :

    public function addComment($creatable, $comment)
    {
            $this->comments()->make(['comment' => $comment])
                ->creatable()->associate($creatable)
                ->save();
    }
    
    推荐文章