对象转换为数组?

时间:2016-10-13 18:50:47

标签: laravel laravel-5 eloquent laravel-5.3

我正在尝试更新notification's数据(用于在视图中显示):

$notifications = $user->notifications()->paginate(15);

foreach ($notifications as $notification)
{
    $post = Post::where('id', $notification->data['post_id'])
        ->first();
    $notification->data = $post;
}

但是当我在我看来这样做时:

@foreach ($notifications as $notification)
    {{ gettype($notification->data) }}
@endforeach

它显示数据是一个数组。为什么它将Post模型对象转换为数组?如何阻止这种情况发生?

2 个答案:

答案 0 :(得分:0)

您的$notification对象是Illuminate\Notifications\DatabaseNotification的实例。这是一个Eloquent Model,它定义了以下$casts属性:

protected $casts = [
    'data' => 'array',
    'read_at' => 'datetime',
];

因此,当您访问$notification->data时,它将自动转换为数组。

要解决您的问题并减少数据库查询的数量,您应该只构建一个单独的帖子查找集合,并将其传递到视图中。

首先,构建一个包含所有Post个ID的数组。然后,运行一个查询以获取这些ID的所有Post | s。之后,通过id重新键入生成的Collection Post | s,以便以后在视图中轻松查找。请务必将Collection Post | $notifications = $user->notifications()->paginate(15); $postIds = []; foreach ($notifications as $notification) { $postIds[] = $notification->data['post_id']; } $posts = Post::whereIn('id', array_unique($postIds))->get()->keyBy('id'); 传递给视图。

@foreach ($notifications as $notification)
    {{ $posts->get($notification->data['post_id']) }}
@endforeach

然后,在您看来:

for (i=0; i<=Employees.length; i++)

答案 1 :(得分:-1)

您没有更新$通知,这就是您看到旧数组而不是您想要保存的新对象的原因。

foreach ($notifications as $key => $notification)
{
   $post = Post::where('id', $notification->data['post_id'])->first();
   $notifications[$key]->data = $post;
}