我正在创建一个Restful应用程序,所以我收到了一个看起来像这样的POST请求
$_POST = array (
'person' => array (
'id' => '1',
'name' => 'John Smith',
'age' => '45',
'city' => array (
'id' => '45',
'name' => 'London',
'country' => 'England',
),
),
);
我想保存我的人员模型并设置 city_id 。
我知道最简单的方法是使用 $ person-> city_id = $ request [' city'] [' id]; 手动设置这种方式对我没有帮助....这段代码只是一个例子,在我的真实代码中,我的模型有15种关系
有没有办法在类似的内容中使用 $ person-> fill($ request); ?
我的模特看起来像:
城市
class City extends Model {
public $timestamps = false;
public $guarded= ['id'];//Used in order to prevent filling from mass assignment
public function people(){
return $this->hasMany('App\Models\Person', 'city_id');
}
}
人
class Person extends Model {
public $timestamps = false;
public $guarded= ['id'];//Used in order to prevent filling from mass assignment
public function city(){
return $this->belongsTo('App\Models\City', 'city_id');
}
public static function savePerson($request){//Im sending a Request::all() from parameter
$person = isset($request['id']) ? self::find($request['id']) : new self();
$person->fill($request);//This won't work since my $request array is multi dimentional
$person->save();
return $person;
}
}
答案 0 :(得分:1)
这有点棘手,但您可以在模型中覆盖Get-Content
方法,并设置fill
以存储将在请求中查找的属性
deeplyNestedAttributes()