【问题标题】:How to turn a collection into an array in laravel如何在laravel中将集合变成数组
【发布时间】:2020-08-13 12:36:10
【问题描述】:

我不确定我的标题是否正确,但我想做的是获取用户未阅读的所有通知。 我有 2 个表,第一个表是通知,第二个是 read_notifications。

这是我在 User.php 模型中的代码

$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
$unread = Notification::whereNotIn('id', $read)->get();

在这里,我获取了 read_notifications 表中的所有通知 ID,我想将它们放入 $unread 语句中。

我这样做时得到的错误是

stdClass 类的对象无法转换为字符串

【问题讨论】:

  • 这能回答你的问题吗? laravel collection to array
  • 我确实尝试过,但我仍然遇到同样的错误
  • NotificationReadNotification 之间是否设置了关系?有ReadNotification 模型吗?我认为可以使用 whereDoesntHave 方法通过正确设置关系来完成。

标签: laravel laravel-7


【解决方案1】:
Notification::whereNotIn('id', $read)->get();

$read 是一个对象,id 应该是一个字符串(或整数)。您应该使用$read 对象中的id 字段,例如$read[$i]->id

另外,whereNotIn 需要一个数组作为第二个参数,因此您需要将您的 ID 从$read 收集到一个类似[1,2,3] 的数组中。

【讨论】:

  • 这就是我想要做的,我试图让我的 id 看起来像 [1,2,3],这样我就可以在 whereNotIn 语句中使用它
【解决方案2】:

感谢您的帮助。我找到了我需要的东西,我需要使用 pluck 方法。

这是更新的代码

$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->pluck('notification_id');
$unread = Notification::whereNotIn('id', $read)->get();

【讨论】:

    【解决方案3】:

    whereNotIn 工作 $read 应该是一个数组。

     $read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
    foreach($read as $re)
       $ot[] = $re->notification_id;
    $unread = Notification::whereNotIn('id', $ot)->get();
    

    或者你可以使用pluck

     $read = DB::table('read_notifications')->where('user_id', $this->id)->pluck('notification_id');
    
     $unread = Notification::whereNotIn('id', $read)->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2019-01-05
      • 2016-07-14
      相关资源
      最近更新 更多