【问题标题】:convert data fetched from DB to array in laravel将从数据库获取的数据转换为laravel中的数组
【发布时间】:2018-02-18 00:53:39
【问题描述】:

我从表“拍卖”中获取数据

$players = DB::table('auction')->where('id',$id)->get();

我正在以这种形式获取数据

[
  {
    "id": 3,
    "name": "Yogesh Singh",
    "year": "BE",
    "branch": "CE",
    "division": "D",
    "achievements": "College Cricket Team",
    "base_price": 5000000,
    "status": 1,
    "manager": 0
  }
]

现在我需要将这些数据转移到另一个表“团队”中,因此我做到了

DB::table('team')->insert(['player_id' => $id, 'player_type' => $player->player_type, 'name' => $player->name, 'price' => $player->price]);

它会抛出一个错误,指出此集合实例上不存在属性 [player_type]。

我很确定我无法将从数据库中获取的数据转换为数组。

我该怎么做?

【问题讨论】:

  • 在查询生成器之前使用DB::setFetchMode(PDO::FETCH_ASSOC);
  • 这是现在的错误,Class 'App\Http\Controllers\PDO'没找到
  • 您的拍卖表中有 player_type 列吗?您正在尝试获取未知属性
  • 在控制器@YogeshKumarSingh 中添加use PDO 命名空间

标签: php database laravel


【解决方案1】:

Laravel 查询构建器 select 方法返回一个 Collection 类型的变量。每个成员都是 stdclass 类型。

集合有一个 toArraye 成员:

toArray()

请注意此函数返回二维数组。

另一种方法是使用 collection->first 获取集合的第一个成员,并使用这种方法将此 stdclass 转换为数组:php stdClass to array

【讨论】:

    【解决方案2】:

    这是因为 $players 返回 collection,因为您使用了 get()。将其更改为first(),如果存在,它将返回Model 实例。变量名也是 $player ,而不是 $players

    $player = DB::table('auction')->where('id',$id)->first();
    

    现在访问如下数据:

    DB::table('team')->insert(['player_id' => $id, 'player_type' => $player->player_type, 'name' => $player->name, 'price' => $player->price]);
    

    您可以保留get() 并像这样访问数据:

    DB::table('team')->insert(['player_id' => $id, 'player_type' => $player[0]->player_type, 'name' => $player[0]->name, 'price' => $player[0]->price]);
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2021-11-12
      • 1970-01-01
      • 2021-03-24
      • 2017-09-11
      • 2022-12-06
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多