【问题标题】:Undefined index , Unable to fetch columns- Laravel未定义的索引,无法获取列 - Laravel
【发布时间】:2021-10-17 06:46:09
【问题描述】:
 $notification=Notifications::where('status','false')->get();
 $data=$notification->all();
 //dd($data);
 dd($data['notificationTypeName']);

在上面的代码中,Notifications 是模型名称。尝试访问数组$data 的列notificationTypeName 时出现错误Undefined index: notificationTypeName

dd($data) 给出如下输出:

array:4 [
  0 => App\Models\Notifications {#323
    #table: "notifications"
    #fillable: array:6 [
      0 => "notificationTypesId"
      1 => "notificationTypeName"
      2 => "userId"
      3 => "email"
      4 => "status"
      5 => "recipientName"
    ]
    #connection: "pgsql"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:9 [
      "id" => 5
      "notificationTypesId" => 3
      "notificationTypeName" => "Cart Expired"
      "userId" => 1
      "email" => "me.g@k.com"
      "recipientName" => "John"
      "status" => false
      "created_at" => null
      "updated_at" => null
    ]
    #original: array:9 [
      "id" => 5
      "notificationTypesId" => 3
      "notificationTypeName" => "Cart Expired"
      "userId" => 1
      "email" => "me.g@k.com"
      "recipientName" => "John"
      "status" => false
      "created_at" => null
      "updated_at" => null
    ]
    #changes: []
    #casts: []
    #classCastCache: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [
      0 => "*"
    ]
    #enableLoggingModelsEvents: true
    #oldAttributes: []
  }

【问题讨论】:

  • 使用 foreach 从对象中获取数据
  • @RushikeshGanesh 我需要在不使用 foreach 的情况下获取列,因为每次获取时我都需要输出中来自 db 的所有行。这就是我面临的问题。
  • 试试dd($data[0]['notificationTypeName']);
  • 在 $notification 中有多少条记录是单条还是多条

标签: php laravel postgresql eloquent laravel-8


【解决方案1】:

all 方法返回集合表示的底层数组:

看到这个:https://laravel.com/docs/8.x/collections#method-all

所以试试这个:

 dd($data[0]['notificationTypeName']) // if u r not going to use foreach

foreach

foreach( $notifications as $notification)
{
  dd($notification->notificationTypeName);
}

【讨论】:

  • 这行得通。但是我的代码中有另一行,例如tap($data)->update(['status'=>'true']);。现在这段代码显示错误Call to a member function update() on array
  • 尝试使用带有特定索引的tap($data[0]),但如果您不想使用foreach,我建议使用foreach 或更好地通过id 查找通知
猜你喜欢
  • 2018-08-02
  • 2012-08-24
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 2021-10-06
相关资源
最近更新 更多