Laravel雄辩的多维阵列质量分配

时间:2016-04-12 18:02:37

标签: php laravel eloquent mass-assignment

我正在创建一个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;
}

}

1 个答案:

答案 0 :(得分:1)

这有点棘手,但您可以在模型中覆盖Get-Content方法,并设置fill以存储将在请求中查找的属性

deeplyNestedAttributes()