【问题标题】:Laravel mass assignment won't fill fieldsLaravel 质量分配不会填充字段
【发布时间】:2013-06-02 15:31:00
【问题描述】:

我有一个似乎不能批量分配的模型,即使我已经填写了$fillable 字段:

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
    • 身份证
    • user_id
    • remote_addr
    • user_agent
    • 成功
    • created_at
    • updated_at

当我用这些变量批量分配实例时,

$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 作为文档描述的 - 为什么在这种情况下批量分配不起作用?

【问题讨论】:

  • 感谢这个很好的工作代码示例。 :)

标签: php laravel laravel-4 mass-assignment


【解决方案1】:

原来这是 Laravel 中的 a bug(一直是 fixed) - 默认情况下所有字段都受到保护(protected $guarded = array('*');),然后优先于 $fillable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多