Laravel与Eloquent不会在数据库上保存模型属性 [英] Laravel with Eloquent doesn't save model properties on database
问题描述
我正在使用php laravel框架构建一个Web应用程序.当我将模型保存在数据库中时,它会插入但不保存模型属性.我看不到解决方法,因为laravel日志未显示任何错误.有什么主意吗?
I'm buiding an web app using php laravel framework. When I save the model on the database it makes an insert but doesn't save model properties. I can't see how to fix because the laravel log doesn't show any mistake. Any idea?
有模型:
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'test';
// protected $fillable = array('name', 'surname', 'mobile', 'phone', 'mail', 'adress');
// Model properties
private $name;
private $surname;
private $mobile;
private $phone;
private $mail;
private $adress;
// Model constructor
function __construct($name, $surname, $mobile, $phone, $mail, $adress) {
$this->name = $name;
$this->surname = $surname;
$this->mobile = $mobile;
$this->phone = $phone;
$this->mail = $mail;
$this->adress = $adress;
}
还有用于创建User对象并将其保存到数据库中的php代码
And there's php code which create User object and save it to the database
<?php
// Create an object using model's constructor
$user = new User('John', 'Doe', 685412578, 9354784125, 'j@doe.com', 'Portland');
// Show some properties
echo '<p>'.$user->getName().'</p>';
echo '<p>'.$user->getSurname().'</p>';
// Saving model on database
$user->save();
?>
当我执行屏幕上显示的php代码时,模型属性并进行插入,但不保存属性.如果有人可以帮助我,那就太好了:)
When I execute the php code show on screen the model properties and makes an insert but doesn't save the properties. Would be great if someone can help me :)
有解决方案(如果有人遇到相同或相似的问题)
There's is the solution (if someone has the same problem or similar)
型号:
protected $table = 'test';
// Fields on databse to save model properties
protected $fillable = array('name', 'surname', 'mobile', 'phone', 'mail', 'adress');
// Model properties
private $name;
private $surname;
private $mobile;
private $phone;
private $mail;
private $adress;
和php代码:
<?php
// Create an object
$user = User::create(array(
'name'=>'John',
'surname'=>'Doe',
'mobile'=>685412578,
'phone'=>9354784125,
'mail'=>'j@doe.com',
'adress'=>'Portland'
));
// Show some properties
echo '<p>'.$user->name.'</p>';
echo '<p>'.$user->surname.'</p>';
// Saving model on database
$user->save();
?>
推荐答案
如 http:/中所述/laravel.com/docs/eloquent#mass-assignment ,您需要为要批量分配的所有属性设置$fillable
属性.因此,您应该取消注释以protected $fillable = ...
开头的行.
As described at http://laravel.com/docs/eloquent#mass-assignment, you need the $fillable
property set for all the properties you want to be mass-assignable. You should therefore uncomment the line starting with protected $fillable = ...
.
这篇关于Laravel与Eloquent不会在数据库上保存模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!