我需要读出的数据透视表条目中pivot_created_at
时间戳的值。
访问数据透视表数据已经完成,我使用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
条目以读取时间戳?我现在有点陷入困境。
答案 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;
}