【问题标题】:Struggling with Laravel's morphable relationships与 Laravel 的可变形关系作斗争
【发布时间】:2021-06-24 15:29:00
【问题描述】:

在一个项目中,假设我们有客户,每个客户可以拥有一张 Voucher。不过,对于不同的客户,代金券可能是不同的东西 - 可能是酒店、汽车或航班。

我们有一张机票代金券代码表、一张酒店代金券代码表和一张汽车代金券代码表。

因此,当客户获得优惠券时,我们为他们分配了下一个代码,用于他们获得优惠券的相关事物。但与其有多个表(customer_car_voucher、customer_hotel_voucher 等),我更愿意有一个 Voucher 表,该表又链接到相关的凭证类型。

我想要做的只是去 $customer->voucher->code 获取相关代码,无论是航班、酒店还是汽车。你看,其他代金券可能会在以后添加,用于不同的事情。

我想我可以使用可变形关系来做到这一点 - 凭证变形到汽车、酒店和航班,所以在凭证表中有一个“voucherable_type”和一个“voucherable_id”。但该死的,如果我能让它工作的话。

有什么帮助吗?我是不是搞错了?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    你说得对。并用于提示:

      public function customer()
      {
        return $this->belongsTo(Customer::class):
      }
    
      public function voucherable()
      {
        return $this->morphTo();
      }
    

    在凭证模型中。

    每个航班、汽车、酒店包括:

    public function voucher(){
        return $this->morphOne(Voucher::class,'voucherable');
    }
    

    您也可以查看Laravel morph relationship 以获得更多帮助。

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 1970-01-01
      • 2019-02-10
      • 2022-11-15
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多