Laravel |变形模型的多态关系

时间:2019-05-15 14:12:09

标签: laravel polymorphism

我正在创建一个默认为null的多态关系,因为它最初没有关联。

然后创建关联,并希望能够更新多态表以在原始类和变形类之间建立链接。

post_images:

| id | post_id | width | height | created_at | updated_at

文件:

| id | fileable_type | fileable_id | file_disk_id | created_at | updated_at

因此,基本上,在多态表内部,它们的类型和id默认为null,因为必须先对其进行处理并转换为标准格式,等等。

然后我在变形表内部创建关联的行,但是我不确定如何更新多态以使其具有变形表中的类型和ID。

我尝试做类似$post->images()->create(...);的事情,然后尝试做类似$file->where('id', $fileId)->firstOrFail()->associate($post);的事情,但这似乎返回null。

所以当前的过程是:

上传文件->在文件表中创建一行,其中包含多态关系,但列默认为空。

标准化文件->然后将文件转换并压缩为用于站点的标准格式。

创建post_images行->然后,网站为post_images表创建一行,然后需要链接更新文件行以包含新的多态关系。

雄辩的关系:

File.php

public function fileable()
{
    return $this->morphTo();
}

PostImage.php

public function file()
{
    return $this->morphMany(File::class, 'fileable');
}

Post.php

public function images()
{
    return $this->hasMany(PostImage::class);
}

1 个答案:

答案 0 :(得分:1)

认为,您应该只能在关系上调用save方法。例如:

$post->file()->save($file)
相关问题