【问题标题】:Laravel Pivot table extra date-time field format (Not timestamp) using carbon object使用碳对象的 Laravel 数据透视表额外的日期时间字段格式(不是时间戳)
【发布时间】:2014-08-28 00:07:35
【问题描述】:

我的应用中有一个数据透视表 ('offer_usage_detail'),该表有 4 个字段,如下所示

id          int           AutoIncrement
user_id     int           reference to user table
offer_id    int           reference to offer table
use_date    date-time     Store date time when user use offer

我需要以d-m-Y H:i 格式显示使用过优惠的用户列表。

所以我在我的报价模型中添加了以下代码

 public function user() {
    return $this->belongsToMany('User', 'offer_usage_detail', 'offer_id', 'user_id')->withPivot('use_time');
}

目前我正在使用核心 php 的 date 函数和 strtotime 来格式化日期时间,但我想知道有没有办法将数据透视表的日期时间字段转换为碳对象。

我尝试将use_time 字段放入Offer Modelprotected $dates = array('created_at','use_time');,但没有成功。

如果列是日期时间字段,是否可以将额外的数据透视表列转换为碳对象?

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    我建议的最佳解决方案是为此关系创建自定义枢轴模型:

    // Offer model (the same goes for the User model, but change to 'instanceof Offer`
    public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
    {
        if ($parent instanceof User) return new OfferUserPivot($parent, $attributes, $table, $exists);
    
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
    
    // OfferUserPivot
    use Illuminate\Database\Eloquent\Relations\Pivot;
    
    class OfferUserPivot extends Pivot {
       // override either property:
       protected $dates = ['use_time'];
    
       // or method:
       // public function getDates()
       // {
       //   return ['use_time']; // and other columns like created_at etc if you like
       // }
    }
    
    // Then you can do this:
    $user->offers->first()->pivot->useTime; // Carbon object
    $offer->users->first()->pivot->useTime; // Carbon object
    

    【讨论】:

    • 好主意,但我有疑问:我们不能不使用枢轴模型吗?
    • 是的,您可以设置访问器,例如检查$this->pivot 是否不为空(它在关系的上下文中),然后返回->pivot->useTime 突变为Carbon,但您需要在两种模型上都这样做,这绝对是更糟糕的解决方案。为什么你不想要那个枢轴模型?
    • 我可以使用枢轴模型,只是好奇有没有什么办法......谢谢我已经使用了你的解决方案:)
    【解决方案2】:

    你可以试试这个解决方案。

    return $this->belongsToMany('App\Role')->withTimestamps();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-15
      • 2016-02-13
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多