【问题标题】:laravel polymorphic relation custom typelaravel 多态关系自定义类型
【发布时间】:2020-04-25 01:02:41
【问题描述】:

我有一个 Image 表如下:

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 定义自定义类型,但是是否可以定义两个指向同一个 Model 的不同类型并使用这些类型来过滤结果?

【问题讨论】:

  • 您打算如何为给定帖子的任何图像存储type 信息?
  • "imageable_type" 是连接模型名称和图像用例的结果。 “imageable_type”的几个例子是:“post/content”或“post/cover”

标签: laravel eloquent


【解决方案1】:

您可以根据需要使用扩展关系进行过滤。

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

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

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

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

【讨论】:

  • 因为这些关系在 imageable_type 上有字符串 post,它可能对其他模型没有用处。要使所有这些模型正常工作,您可以从图像类型中删除 post/ 前缀。
  • images 关系应该如何定义?是多态关系吗?
  • images 定义为 Laravel 建议的正常多态关系。 public function images() { return $this->morphMany(Image::class, 'imageable'); }
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2019-02-09
  • 2017-01-05
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多