拉拉维尔多态关系自定义类型



>我有一个图像表如下:

Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('path');
$table->unsignedBigInteger('imageable_id')->nullable();
$table->string('imageable_type')->nullable();
$table->unsignedBigInteger('image_properties_id')->nullable();
$table->unsignedBigInteger('parent_id')->nullable();
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});

我想与图像表建立多态关系,它适用于大多数部分,但是这里的问题是某些模型(例如Post(可以具有用于不同目的的图像,例如帖子可以具有用于帖子封面的图像以及帖子内容中使用的图像。 是否可以仅访问属于帖子封面的图像而不能访问内容?

我知道我可以使用 morphmap 定义自定义类型,但是是否可以定义指向同一模型的两种不同类型并使用这些类型来过滤结果?

可以使用扩展关系根据需要进行筛选。

假设您在Post模型上具有images关系,则可以再创建两个,如下所示(内容和封面各一个(

public function coverImages() {
return $this->images()->where('imageable_type', 'post/cover');
}
public function contentImages() {
return $this->images()->where('imageable_type', 'post/content');
}

通过这些关系定义,现在您可以将它们中的每一个用作独立的雄辩关系。

最新更新