【发布时间】:2016-04-12 18:02:37
【问题描述】:
我正在创建一个 Restful 应用程序,所以我收到了一个看起来像这样的 POST 请求
$_POST = array (
'person' => array (
'id' => '1',
'name' => 'John Smith',
'age' => '45',
'city' => array (
'id' => '45',
'name' => 'London',
'country' => 'England',
),
),
);
我想保存我的 person 模型并设置它的 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;
}
}
【问题讨论】:
-
你试过 Laravel 批量赋值吗?由于您的请求包含一系列信息。 laravel.com/docs/5.1/eloquent#inserting-and-updating-models
-
是的,我已经试过了……
$person->fill($request);这句话是表达集体任务的另一种方式。问题不是大量分配字段属性。问题是试图自动保存具有与模型相关的 id 的属性。在我的示例案例中,我将模型城市作为模型,并且该模型包含它的 id...那么为什么不从我的城市模型中设置我的人模型的 city_id 呢?
标签: php laravel eloquent mass-assignment