对象被转换为数组?

Object getting converted to array?

我正在尝试更新 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 模型对象转换为数组,我该如何阻止这种情况发生?

您没有在 $notifications 中更新,这就是为什么您看到的是旧数组而不是您要保存的新对象。

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

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

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

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

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

首先,构建所有 Post id 的数组。然后,运行 一个查询来获取这些 ID 的所有 Post|s。之后,通过 id 重新键入 Post|s 的结果 Collection,以便稍后在视图中轻松查找。确保将 Post| 中的 Collection 传递给视图。

$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