2017-10-06 15 views
0

に基づいた日付を返します。Laravel 5 /雄弁は、私は2つのテーブルを持っているCREATED_ON列プラス可変時間

状態表3のカラムがあります。IDは、期間

status_logs表は、3つの列を有している:IDは、のcreated_at

をSTATUS_ID

私はこのような2つのモデルを持っています:

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 
    } 
}] 

は、私はこれをどのように行うのでしょうか?カーボン(http://carbon.nesbot.com/docs/#api-addsub)を使用して

答えて

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

、あなたのためにこの作品のようなものを行います。

$log->finished_at = $log->created_at->addHours($log->statuses()->duration); 
0

最初のステップは、このような炭素 を用いて使用のcreated_at値で分け期間を追加24 における持続devideあります。

$log->finished_at = $log->created_at->addDays($log->statuses()->duration/24); 
$log->save(); 
関連する問題