2017-10-06 130 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();