Laravel数据透视表额外的日期时间字段格式(非时间戳),使用碳对象

问题描述 投票:5回答:2

我的应用程序中有一个数据透视表('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来格式化日期时间,但我想知道有什么方法可以将数据透视表的日期时间字段转换为Carbon对象。

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

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

php laravel laravel-4 eloquent
2个回答
5
投票

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

// 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

0
投票

您可以尝试此解决方案。

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

© www.soinside.com 2019 - 2024. All rights reserved.