我的应用程序中有一个数据透视表('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 Model
的protected $dates = array('created_at','use_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->belongsToMany('App\Role')->withTimestamps();