Laravel Pivot表使用碳对象的额外日期时间字段格式(非时间戳)

Rav*_*avi 6 php laravel eloquent laravel-4

我的应用程序中有一个数据透视表('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
Run Code Online (Sandbox Code Playgroud)

我需要以d-m-Y H:i格式显示使用报价的用户列表,其中包含日期和时间.

所以我在我的商品模型中添加了以下代码

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

目前我正在使用核心php的date功能strtotime来格式化日期时间,但我想知道是否有任何方法将数据透视表日期时间字段转换为碳对象.

我试图把use_time场中Offer Modelprotected $dates = array('created_at','use_time');,但它并没有奏效.

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

Jar*_*zyk 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
Run Code Online (Sandbox Code Playgroud)

  • 好主意,但我有疑问:如果不使用枢轴模型,我们不能这样做吗? (2认同)