Eloquent模型不向数据库添加列

时间:2014-07-28 04:54:07

标签: php laravel eloquent

这是一个简单的问题。当我在模型上调用save()时,列不会添加到数据库中。这是我的模特:

class User extends Eloquent implements UserInterface, RemindableInterface {
    use UserTrait, RemindableTrait;

    protected $table = 'users';
    protected $hidden = array('password', 'remember_token');

    public $email; ## string (used as username)
    public $name; ## string
    public $address; ## string
    public $phone; ## string nullable
}

这是添加行

的代码
$data=Input::all();

if ($data['password'] != $data['confirm-password']){
    return Redirect::to('/register');
}

$user = new User;

$user->email=$data['email'];
$user->password=Hash::make($data['password']);
$user->name=$data['first']." ".$data['last'];
$user->address=$data['street'].", ".$data['city'].", ".$data['state']." ".$data['zip'];
$user->phone=$data['phone'];

$user->save();

echo "<pre>";
var_dump($user);
echo "</pre>";

var_dump正在输出模型中的正确值。模型中的每个字段都与数据库中列的名称完全匹配。正在添加密码哈希,并且正在创建新行,但每隔一列都显示为空。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您不能将列声明为对象属性。 Laravel将为您带来魔力。删除这些行:

public $email; ## string (used as username)
public $name; ## string
public $address; ## string
public $phone; ## string nullable

<强>解释

Laravel的Eloquent使用PHP __set()reference),当你设置一个未定义的属性时会触发它。然后,Laravel通过Model::setAttribute()执行一些内部任务,以自己的方式填充模型。

请参阅Illuminate/Database/Eloquent/Model.php

public function __set($key, $value)
{
    $this->setAttribute($key, $value);
}

public function setAttribute($key, $value)
{
    // First we will check for the presence of a mutator for the set operation
    // which simply lets the developers tweak the attribute as it is set on
    // the model, such as "json_encoding" an listing of data for storage.
    if ($this->hasSetMutator($key))
    {
        $method = 'set'.studly_case($key).'Attribute';

        return $this->{$method}($value);
    }

    // If an attribute is listed as a "date", we'll convert it from a DateTime
    // instance into a form proper for storage on the database tables using
    // the connection grammar's date format. We will auto set the values.
    elseif (in_array($key, $this->getDates()))
    {
        if ($value)
        {
            $value = $this->fromDateTime($value);
        }
    }

    $this->attributes[$key] = $value;
}