幫我保存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進行存儲」
我在哪裏錯了?
你的問題不太清楚,請補充更具體的細節?你的代碼做了什麼?並在哪個變量或哪行代碼中獲得哪個輸出? – C2486
在保存之前將它編碼爲JSON? –