Laravel:Eloquent 模型中的多个多态关系

标签 laravel laravel-5 eloquent laravel-5.2

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

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

Eloquent 文件
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))'

提前致谢!!!

最佳答案

您可以使用 make() :

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

关于Laravel:Eloquent 模型中的多个多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52113393/

相关文章:

php - Laravel 5 有条件的多对多同步()

php - 创建时间戳会在构造函数中设置动态表名的模型引发错误

mysql - 如何将此 SQL 查询转换为 Laravel 语法?

php - 非默认守卫在 Laravel 5.5 中被忽略

php - Laravel 架构构建器主键作为外键

javascript - Laravel,无法弄清楚如何使用下拉菜单显示特定年份的主题

php - Laravel : Carbon shorten diffForHumans()

php - Laravel Elixir 没有结合脚本

php - 更改 Laravel 路由参数

php - 按类别 id laravel 检索帖子