[英]How to update array value in laravel
我的控制器代碼:
$userBasicInfoId = $this->userBasicInfo->where('user_id', $userProfile['id'])->value('id');
if($userBasicInfoId) {
$userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
$userBasicInfo->fill($userProfile)->save();
} else {
$userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
}
這是我的userBasicInfo模型值:
protected $table = "user_basic_info";
protected $fillable = [
'first_name', 'middle_name', 'last_name', 'profile_pic', 'date_of_birth', 'gender', 'area_id', 'user_id', 'created_by', 'updated_by', 'created_at', 'deletedAt','title','cell_no','address','ssn','work_phone','fax','extension','primary_facility','affiliated_facility','employed_by','emergency_phone','designation','department','employment_type','biography','hiring_date','from','to'
];
我可以更新值,但問題是我只發送一個字段作為附屬_facility的數組如何更新此值?
我的身體要求:
"user_profile": {
"id": 38,
"email": "shahzad124@ovadamd.com",
"status": 0,
"first_name": "shahzad12",
"middle_name": "Admin",
"last_name": "super",
"date_of_birth": "2015-01-01",
"gender": "M",
"address": "Minhatten NY",
"city": "New York",
"state": "Washington",
"zip": "12312",
"fax": "111-111-1111",
"extension": "2471",
"work_phone": "111-111-1111",
"social_security": "111-11-1111",
"module_id": 2,
"title": "Mr",
"cell_no": "124788",
"ssn": "256",
"primary_facility": 1,
"affiliated_facility": [1],
"employed_by": "john",
"emergency_phone": "57744",
"designation": " supervisor",
"department": "facility",
"employment_type": "Temporary",
"biography": "I am Doctor",
"hiring_date": "2015-01-01",
"from": "2015-01-01",
"to": "2015-01-01",
"image": ""
},
您可以在我的身體請求中看到我發送“affiliated_facility”:[1]當我點擊請求時它說:
"Array to string conversion (SQL: update `user_basic_info` set `gender` = M, `updated_at` = 2019-05-29 18:19:34, `affiliated_facility` = 1 where `id` = 36)"
我如何更新我作為數組發送的特定字段?
我們將非常感謝您的幫助
除非您在SQL中將該字段設置為JSON或類似字段,否則更改您的體系結構可能是最簡單的解決方案。 affiliated_facility
字段看起來應該是一個關系,而不是userBasicInfo模型中的單個字段,因為它可能是許多工具(因為數組可能會返回)。
如果在userBasicInfo模型上設置關系,則類似於:
public function affiliatedFacilities(){
return $this->belongsToMany("App\AffiliatedFacility");
}
然后,當您更新時,您可以自動附加/同步:
$userBasicInfo->affiliatedFacilities()->sync($request->get('affiliated_facility', []));
你可以使用list
函數,但是你必須要小心,因為list
函數可以改變PHP 4到5/7的行為。
例如:
你有數組$array = [1,2,3]
,到目前為止還好嗎?
所以在PHP 4中如果你這樣做:
list($one, $two, $three) = $array
你的輸出將是:
$one = 3, $two = 2, $three = 1
因為在PHP 4中, list
函數從右到左分配值,但是如果你在7中使用輸出它將是反向的,例如:
list($one, $two, $three) = $array
// $one = 1, $two = 2, $three = 4
它會對你的情況有所幫助,否則,我強烈建議你修改你的代碼和結構,如果你的字段affiliated_facility
不是一個數組那么為什么你收到一個呢? 沒有道理嗎?
因此,在您嘗試“接近”PHP的解決方案之前,我強烈建議您修改邏輯。
有關該功能的更多參考,請參閱文檔: https : //www.php.net/manual/en/function.list.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.