【问题标题】:Laravel Eloquent: Polymorphic One-to-...well, it dependsLaravel Eloquent:多态的一对...好吧,这取决于
【发布时间】:2014-06-20 10:10:05
【问题描述】:

我有 3 个模型(产品、类别、图片)。一个产品可以有多个图像,一个类别应该有一个图像。这对我来说听起来像是多态关系,但我只是不确定我想要的设置方式是否真的有效。

我可以对 Product 进行一对多,对 Category 上的同一多态字段进行一对一吗?还是我需要将两者都设为一对多关系,并在每次需要类别图像时使用->first()

我不是 100% 既定的多态关系,我的头在试图弄清楚我需要如何设置 3 个模型时有点晕头转向,因此非常感谢任何形式的解释 :)

【问题讨论】:

  • 这周我实际上遇到了同样的问题。现在,我正在按照您的建议对类别图像执行 ->first() 。我找不到更好的解决方案 - 但如果其他人有,我很感兴趣。

标签: laravel laravel-4 polymorphism eloquent


【解决方案1】:

它只是有效,除非我误解了你的意图..

// Image model
public function imageable()
{
   return $this->morphTo();
}

---

// Product model
public function images()
{
   return $this->morphMany('Image', 'imageable');
}
// you can have this one too (default image for example)
public function image()
{
   return $this->morphOne('Image', 'imageable');
}

---

// Category model
public function image()
{
   return $this->morphOne('Image', 'imageable');
}

---
// Usage:

$product = Product::first();
$product->image; // first Image model
$product->images; // Collection of Image models

$category = Category::first();
$category->image; // the only Image model

【讨论】:

    猜你喜欢
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2021-06-16
    • 2017-04-20
    相关资源
    最近更新 更多