2017-09-22 244 views
1

幫我保存json到db。表字段類型 - 文本。 我有模型澆鑄陣列Laravel 5.4將json保存到數據庫

class Salesteam extends Model 
{ 
    protected $casts = [   
     'team_members' => 'array' 
    ]; 
} 

我想要得到的JSON這樣{「指標」:「用戶id」},並將其存儲到數據庫中。 例子:

{"1":"7","2":"14","3":"25","4":"11"} 

我有銷售組型號和「team_members」以dB爲單位列保存所有用戶ID屬於這個團隊。 我的代碼通過ID查找團隊,獲取所有'team_members'屬性併爲該團隊添加新用戶。我希望以json格式存儲所有用戶並在添加新用戶標識時增加索引。

銷售組屬性:

"id" => 20 
"salesteam" => "Admin" 
"team_leader" => 0 
"invoice_target" => 884.0 
"invoice_forecast" => 235.0 
"team_members" => "[1,66,71]" 
"leads" => 0 
"quotations" => 0 
"opportunities" => 0 
"notes" => "" 
"user_id" => 1 
"created_at" => "2017-09-22 09:13:33" 
"updated_at" => "2017-09-22 13:10:25" 
"deleted_at" => null 

代碼來添加新用戶團隊:

$salesTeam = $this->model->find($salesTeamId); 
$teamMembers = $salesTeam->team_members; 
$teamMembers[] = $userId; 
$salesTeam->team_members = $teamMembers; 
$salesTeam->save(); 

但它存儲到數據庫陣列並沒有指數

"team_members" => "[1,34,56]" 

從Laravel文檔 - Array & JSON Casting 「數組將自動被序列化回JSON進行存儲」

我在哪裏錯了?

+0

你的問題不太清楚,請補充更具體的細節?你的代碼做了什麼?並在哪個變量或哪行代碼中獲得哪個輸出? – C2486

+0

在保存之前將它編碼爲JSON? –

回答

0

,如果你得到這個"[1,34,56]"只是做json_decode($team_members)

,你就會有這樣的:

array:3 [▼ 
    0 => 1 
    1 => 34 
    2 => 56 
] 
1

爲了使JSON字符串這樣

{"1":"7","2":"14","3":"25","4":"11"} 

php,你必須通過關鍵,當你推動元素到數組。例如

$teamMembers = []; 
$teamMembers['1'] = 7; 
$teamMembers['2'] = 14; 
... 

如果你不讓它的associative arrayphp將轉換爲JSON字符串時,認爲這是JSON數組..

提示:您可以通過只需一個鍵,它會工作太。 例如

$test = [1, 2, 3, 4, 5, 6]; 

$test['10'] = 56; 

echo json_encode($test); 

輸出:

"{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"10":56}" 

PHP-Reference

0

簡單的解決方案

$books = App\Book::all(); 
$user->books = $books->toJson(); 
$user->save(); //example: userid -> 2 

$user = App\User::find(2); 
$userBooks = json_decode($user->books, true); // to generate object again