Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用carbon对象的Laravel Pivot表额外日期时间字段格式(非时间戳)_Php_Laravel_Laravel 4_Eloquent - Fatal编程技术网

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

Php 使用carbon对象的Laravel Pivot表额外日期时间字段格式(非时间戳),php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我的应用程序中有一个数据透视表(“提供\使用\详细信息”),该表有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 我需要

我的应用程序中有一个数据透视表(“提供\使用\详细信息”),该表有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
函数和
strotime
来格式化日期时间,但我想知道是否有任何方法可以将Pivot表的日期时间字段转换为carbon对象

我尝试将
use\u time
字段放入
Offer Model
protected$dates=array('created\u at','use\u time')但它不起作用


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

我建议的最佳解决方案是为该关系创建自定义透视模型:

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

你可以试试这个解决方案


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

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