【发布时间】:2018-08-23 04:45:02
【问题描述】:
我正在构建一个包含 4 个表的应用程序:Films、Actors、Categories 和 Images 一侧的图像与另一侧的电影、演员和类别之间存在多态关系。
这些是我的模型:
- Actor
class Actor extends Model
{
protected $fillable = ['name', 'image_id', 'genre', 'slug',];
public function images()
{
return $this->morphMany('App\Comment', 'imageable');
}
}
- Category
class Category extends Model
{
protected $fillable = [ 'category', 'description', 'image_id', 'slug'];
public function images()
{
return $this->morphMany('App\Comment', 'imageable');
}
}
- Film
class Film extends Model
{
protected $fillable = ['name','image_id','description','slug','trailer','year','duration','age_id','language_id','category_id'];
public function images()
{
return $this->morphMany('App\Comment', 'imageable');
}
}
- Images
class Image extends Model
{
protected $fillable = [ 'image', 'imageable_id', 'imageable_type' ];
public function imageable()
{
return $this->morphTo();.
}
}
据我了解,Images 表中的“imageable_id”是其他表(film->id、category->id 或 actor->id)中位置的 id(INCREMENT)
但“imageable_id”也必须是唯一的。
这是我的问题:
假设我制作了第一部电影并将图像与之关联。
Image.id = 1, imageable_id = 1 (the id of the film), imageable_type = film
其次,我创建一个演员并将一个图像与其关联。
Image.id = 2, imageable_id = 1 (the id of the actor).... <-- ERROR
SQLSTATE[23000]:违反完整性约束:1062 键“images_imageable_id_unique”的重复条目“7”
我应该删除所有表中的 AUTO_INCREMENT 吗?
知道如何解决这个问题吗?
我的 3 个控制器(CategoriesController、FilmsControllers 和 ActorControllers)中的 Store 方法是相似的。 (我在这里只分享 Categoriescontrollers)
public function store(CategoriesRequest $request)
{
$file = $request->file('image');
$name = time() . '-' . $file->getClientOriginalName();
$file->move('images', $name);
$last_img = Image::orderBy('id', 'desc')->first();
$category = Category::create([
'category' => $request->category,
'description' => $request->description,
'slug' => str_slug($request->category, '-'),
'image_id' => $last_img->id + 1,
]);
$image = Image::create([
'image' => $name,
'imageable_type' => 'Category',
'imageable_id' => $category->id
]);
$category->save();
Session::flash('success', 'Category successfully created!');
return redirect()->route('categories.index');
}
【问题讨论】:
-
你应该删除你的 imageable_id 的唯一约束,与自动增量无关。
-
谢谢,它解决了这个问题。我认为 imeable_id 必须是唯一的
标签: laravel polymorphic-associations laravel-eloquent