【问题标题】:Laravel hasMany with where in a Polymorphic relationshipLaravel hasMany 与 where 在多态关系中
【发布时间】:2014-12-13 13:27:01
【问题描述】:

我有 3 张桌子,汽车、公寓和商店。每张桌子都有照片。照片存储在数据库中。我只想为照片使用一张表,我不想为每个 Cars、Flats 和 Shops 创建 Photos 表。

照片表结构是这样的;

| id |           photo_url        | type  | destination_id |
------------------------------------------------------------
  1  |   http://example.com/1.jpg | Cars  |      1         |
  2  |   http://example.com/2.jpg | Flats |      1         |
  3  |   http://example.com/3.jpg | Flats |      2         |
  4  |   http://example.com/4.jpg | Shops |      1         |
  5  |   http://example.com/3.jpg | Shops |      2         |

我需要在 Shops、Flats 和 Cars 模型类中定义 hasMany 与类型的关系。

这样做的正确方法是什么?

【问题讨论】:

    标签: laravel orm laravel-4 eloquent


    【解决方案1】:

    您可以将关系对象视为查询,因为您可以使用它们调用查询构建函数。下面的示例应该让您朝着正确的方向前进。

    class Cars extends Eloquent
    {
        function photos()
        {
            return $this->hasMany('Photo')->where('photos.type', '=', 'Cars');
        }
    }
    

    【讨论】:

    • 非常感谢,我需要打电话给Order::with('orderItems')->where('orderItems.type',1)->with('orderItems.orderItemOptions', 'orderItems.orderMenuItems')->first(),但范围不能那样工作
    • 哪种方法最好,第一种方法还是第二种方法??
    • 有什么方法可以为此传递参数吗?在 where 子句中使用参数?
    • @Logan 我们如何使用WITH function在这个函数中传递一个参数,你能解释一下吗?
    • 如果需要给"with"添加条件,用with((['Model' => function ($query) { $query->where('title', 'like', '%第一个%'); }]))
    【解决方案2】:

    您可以使用 Eloquent 的Polymorphic relationships。 Laravel 文档中的示例实际上展示了为多个模型设置一个通用图像表,因此这应该为您指明正确的方向。在您的情况下,您的模型看起来像这样:

    class Photo extends Eloquent {
    
        public function imageable()
        {
            return $this->morphTo();
        }
    
    }
    
    class Car extends Eloquent {
    
        public function photos()
        {
            return $this->morphMany('Photo', 'imageable');
        }
    
    }
    
    class Flat extends Eloquent {
    
        public function photos()
        {
            return $this->morphMany('Photo', 'imageable');
        }
    
    }
    
    class Shop extends Eloquent {
    
        public function photos()
        {
            return $this->morphMany('Photo', 'imageable');
        }
    
    }
    

    您可以访问照片,比如给定的Flat,如下所示:

    Flat::find($id)->photos;
    

    为此,您还需要在 photos 表中添加 2 个额外的列:

    imageable_id: integer  <-- This will be the ID of the model
    imageable_type: string <-- This will be the model's class name (Car/Flat/Shop)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 2021-09-24
      • 1970-01-01
      • 2021-07-30
      • 2021-10-13
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      相关资源
      最近更新 更多