2017-09-09 62 views
0

我拿來從表「拍賣」轉換獲取從數據庫到陣列數據laravel

$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]); 

它會拋出一個錯誤,說這個公司不存在Property [player_type]選舉實例。

我很確定我無法將從數據庫獲取的數據轉換爲數組。

我該怎麼做?

+0

使用'DB ::調用setFetchMode(PDO :: FETCH_ASSOC);'查詢生成器 –

+0

之前,這是錯誤現在,類'應用程序\ HTTP \ \控制器PDO '沒有找到 –

+0

你在你的拍賣表有player_type列?您正在嘗試獲取未知屬性 –

回答

1

laravel qurybuilder select方法返回一個Collection類型的變量。每個成員都是st​​dclass類型。 集合有一個toArraye成員: toArray() 只是注意到這個函數返回2維數組。

另一種方法是使用收藏 - >第一個拿到收集的第一件和使用這種方法這stdClass的轉換成數組:php stdClass to array

0

這是因爲$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]); 

OR

可以保持get()和訪問數據是這樣的:

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

希望它有幫助。