Laravel 5/Eloquent - 根据created_on列加可变小时返回日期
问题描述:
我有两个表:状态和status_logs。Laravel 5/Eloquent - 根据created_on列加可变小时返回日期
的状态表有3列:ID,名,时间
的status_logs表有3列:ID,STATUS_ID,created_at
我有两个看起来像这样的模型:
class Status extends Model{
// Name of our database table
protected $table = 'statuses';
// Defines the relationship between this table and the status_logs table
public function status_logs(){
return $this->hasMany('App\Models\Status', 'status_id');
}
}
class StatusLog extends Model{
// Name of our database table
protected $table = 'status_logs';
// Defines the relationship between this table and the statuses table
public function statuses(){
return $this->belongsTo('App\Models\Status', 'status_id');
}
}
我可以用得到两个表的数据:
StatusLog::with('status')->get();
结果看起来是这样的:
"status_logs": [{
"id": 1,
"status_id": 1,
"created_at": "02:34:53 10/5/2017",
"statuses": {
"id": 1,
"name": "started"
"duration": 48
}
}]
我想添加一列名为finish_at到status_logs数组中的每个对象。此日期时间将是created_at值加上任何整数值持续时间是。 持续时间是我们需要添加到created_at以获得值finish_at的小时数。
结果应该是这样的:
"status_logs": [{
"id": 1,
"status_id": 1,
"created_at": "02:34:53 10/5/2017",
"finish_at": "02:34:53 10/7/2017",
"statuses": {
"id": 1,
"name": "started"
"duration": 48
}
}]
我将如何做到这一点?
答
使用Eloquent appends将解决这个问题。
添加附加属性并定义值。它将如下所示。
class StatusLog extends Model
{
protected $appends = ['finish_at'];
public function getFinishedAtAttribute()
{
// carbon to add hours
$dt = Carbon::instance($this->attributes['created_at']);
$dt->addHours($this->statuses->duration);
return $dt->toDateTimeString(); // change to your desire format
}
}
答
采用碳(http://carbon.nesbot.com/docs/#api-addsub),做这样的事情对你的工作:
$log->finished_at = $log->created_at->addHours($log->statuses()->duration);
答
第一步是devide在24 持续时间然后在created_at值使用碳 像这样的使用添加devided持续时间。
$log->finished_at = $log->created_at->addDays($log->statuses()->duration/24);
$log->save();