Laravel质量分配不会填写字段 [英] Laravel mass assignment won't fill fields

查看:70
本文介绍了Laravel质量分配不会填写字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我已经填写了$fillable字段,我的模型似乎也无法大规模分配:

I have a model that doesn't seem to be mass assignable, even though I have filled in the $fillable fields:

class LoginAttempt extends Eloquent
{
    protected $table = 'login_history';
    protected $fillable = array('remote_addr', 'user_agent', 'successful');

    public function user()
    {
        return $this->belongsTo('User');
    }
}

正在使用以下架构:

  • login_history
    • id
    • user_id
    • remote_addr
    • user_agent
    • 成功
    • created_at
    • updated_at
    • login_history
      • id
      • user_id
      • remote_addr
      • user_agent
      • successful
      • created_at
      • updated_at

      当我为这些实例分配大量变量时,

      When I mass assign the instance with these variables,

      $vars = array(
          'remote_addr' => $_SERVER['REMOTE_ADDR'],
          'user_agent' => $_SERVER['HTTP_USER_AGENT'],
          'successful' => false,
      );
      
      print_r($vars);
      => array('remote_addr' => '127.0.0.1', 'user_agent' => 'Moz..', 'successful' => false);
      
      new LoginAttempt($vars);
      => LoginAttempt instance, attributes => array()
      
      LoginAttempt::create($vars);
      => LoginAttempt instance, attributes => array()
      
      $login = new LoginAttempt;
      $login->fill($vars);
      => LoginAttempt instance, attributes => array()
      
      $login = new LoginAttempt;
      $login->remote_addr = $vars['remote_addr'];
      $login->user_agent= $vars['user_agent'];
      $login->successful= $vars['successful'];
      => LoginAttempt instance, attributes => array('remote_addr' => '..', 'user_agent' => '..', 'successful' => false)
      

      我认为我使用的是文档描述的$fillable-为什么在这种情况下批量分配不起作用?

      I think I'm using $fillable as the docs describe - why isn't mass assignment working in this case?

      推荐答案

      原来是一个错误在Laravel中(已已修复)-默认情况下,所有字段均受保护( protected $guarded = array('*');),然后优先于$fillable.

      Turns out this was a bug in Laravel (has been fixed) - all fields are guarded by default (protected $guarded = array('*');) which then took precedence over $fillable.

      这篇关于Laravel质量分配不会填写字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆