【问题标题】:Update Laravel Eloquent ORM with array使用数组更新 Laravel Eloquent ORM
【发布时间】:2013-12-24 02:12:20
【问题描述】:

我试图弄清楚如何从数组中更新和 Eloquent ORM 模态。而不是逐个领域。这是我目前所拥有的。

public static function updatePatient($id){
    $patient_payload = Input::all();  // eg. array('patient_first_name'=>'Test', 'patient_last_name'=>'TEST')
    $patient_to_update = Patient::find($id);

    /*
    |--------------------------------------------------------------------------
    | Validate the request
    |--------------------------------------------------------------------------
    */
    if(!$patient_to_update)
        return Response::json(array('error'=>'No patient found for id given'), 400);

    /*
    |--------------------------------------------------------------------------
    | Update the patient entry.
    |--------------------------------------------------------------------------
    */


    $patient_to_update->update($patient_payload);
    $patient_to_update->save();

    return Response::json(array('success'=>'Patient was updated'));
}

这会引发一个 laravel 模型错误,只是说:'patient_first_name' 是的,patent_first_name 是数据库上的一个 col。作为一种解决方法,我一直在这样做,这很有效。

public static function updatePatient($id){
    $patient_payload = Input::all();
    $patient_to_update = Patient::find($id);

    /*
    |--------------------------------------------------------------------------
    | Validate the request
    |--------------------------------------------------------------------------
    */
    if(!$patient_to_update)
        return Response::json(array('error'=>'No patient found for id given'), 400);

    /*
    |--------------------------------------------------------------------------
    | Update the patient entry. 
    |--------------------------------------------------------------------------
    */


    DB::table('patients')
        ->where('id',$id)
        ->update($patient_payload);

    //update laravel timestamps
    $patient_to_update->touch();        
    return Response::json(array('success'=>'Patient was updated'));
}

【问题讨论】:

  • 你能发布你得到的确切错误吗?

标签: php orm laravel eloquent


【解决方案1】:

由于您要做的是批量分配,我建议您检查您是否在 Patient 模型中定义了 $fillable 属性:

class Patient extends Eloquent {

    protected $fillable = array('patient_payload');

}

作为一项安全措施,Eloquent 不允许您通过批量分配修改任何模型的属性,除非您指定$fillable(允许属性白名单)或$guarded(禁止属性黑名单)。


进一步阅读:

【讨论】:

  • 这很好用。我使用 $guarded 将字段列入白名单。 laravel 在默认情况下可以防止批量分配,这很好。
猜你喜欢
  • 2021-08-28
  • 2016-07-15
  • 2014-01-13
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 2015-02-09
  • 2013-02-12
相关资源
最近更新 更多