2017-10-06 126 views
0

我有两个表:状态status_logsLaravel 5/Eloquent - 根据created_on列加可变小时返回日期

状态表有3列:ID时间

status_logs表有3列:IDSTATUS_IDcreated_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_atstatus_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 
    } 
}] 

我将如何做到这一点?

回答

1

使用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 
    } 
} 
0

第一步是devide在24 持续时间然后在created_at值使用碳 像这样的使用添加devided持续时间。

$log->finished_at = $log->created_at->addDays($log->statuses()->duration/24); 
$log->save();