访问" created_at"数据透视表条目的时间戳

时间:2016-04-18 10:22:17

标签: php laravel eloquent

我需要读出的数据透视表条目中pivot_created_at时间戳的值。

enter image description here

访问数据透视表数据已经完成,我使用Eloquent执行此操作:

    public function states() {
        return $this->belongsToMany('App\Classes\DispatchState')->withTimestamps();
    }

public function getStatesForDispatch($dispatchReference) {
    $dispatch = new Dispatch();
    $dispatch = $dispatch->getDispatch($dispatchReference);
    $statusArray = [];
    $states = $dispatch->states()->get();

    foreach ($states as $status) {
        $statusArray[] = $status;
    }

    return $statusArray;
}

但是如何访问此pivot_created_at条目以读取时间戳?我现在有点陷入困境。

1 个答案:

答案 0 :(得分:2)

来自Documentation。访问数据透视数据的方法是:

$user = User::find(1);

foreach ($user->roles as $role)
{
    echo $role->pivot->created_at;
}

所以在你的情况下,它将是:

public function getStatesForDispatch($dispatchReference) {
    $dispatch = new Dispatch();
    $dispatch = $dispatch->getDispatch($dispatchReference);

    // ->all gets the internal array from the Laravel Collection
    $statusArray = $dispatch->states->all();


    foreach ($statusArray as $status) 
    {
        $createdAt = $status->pivot->created_at;
        // do something with the created_at from the pivot table
    }

    return $statusArray;
}