雄辩的ORM正在生成错误的查询

时间:2014-11-08 22:04:08

标签: laravel laravel-4

我在Laravel 4.2中创建了一个简单的users表,其中包含idname和其他一些字段。在我的控制器中,我试图将用户输入保存为新的用户记录:

$user = new User();
$user->fill($input);
$user->fullname = $input['firstname'] . ' ' . $input['lastname'];
$user->save();

系统产生MySQL错误,因为没有引用任何字符串值。

E.g。

INSERT INTO users (name, ...) VALUES (John, ...)

为什么不引用该值?

感谢。

编辑:

我在User模型中将所有必填字段设置为可填写:

protected $fillable = array('firstname', 'lastname', 'fullname', 'email', 'username', 'birthday', 'gender', 'country', 'city', 'signature', 'confirmed', 'approved');

以下是完整的错误消息:

Illuminate \ Database \ QueryException(HY000)

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'US' for column 'country' at row 1 (SQL: insert into `users` (`firstname`, `lastname`, `email`, `username`, `birthday`, `gender`, `country`, `city`, `signature`, `fullname`, `updated_at`, `created_at`) values (John, Watson, my@email.com, admin, 11/08/2014, male, US, New York, I am the main admin., John Watson, 2014-11-08 17:02:16, 2014-11-08 17:02:16))

再次编辑:

报价不是问题。实际值是问题所在。它期待一个整数,我提供一个字符串。对不起误报。感谢。

1 个答案:

答案 0 :(得分:2)

可能你发现问题(评论说),国家/地区字段需要integer值而不是string,但我会回答另一个问题,即,您正在插入fullname之类的:

$user->fullname = $input['firstname'] . ' ' . $input['lastname'];

在这种情况下,你可以避免这种情况,但可以使用例如fullname;在User模型中,只需声明accessor method,就像这样:

public function getFullNameAttribute()
{
    return $this->firstname . ' ' . $this->lastname;
}

这样你可以实现同样的目的,但不需要在数据库中使用另一个额外的字段,你可以像这样访问动态属性:

echo $SomeUserObject->full_name;

Laravel网站上查看更多内容。