>我有一个模型,它继承自 Toddish\Verify Laravel 包 (https://github.com/Toddish/Verify-L4/blob/master/src/Toddish/Verify/Models/User.php)
我只想添加一些属性:
use ToddishVerifyModelsUser as VerifyUser;
class User extends VerifyUser
{
public function __construct (array $attributes = array()) {
parent::__construct($attributes);
$this->fillable = array_merge ($this->fillable, array(
'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
));
}
}
当我运行测试时:
class UserTest extends TestCase {
public function testUserCreation () {
$user = User::create(
[
'username' => 'testusername',
'email' => 'email@test.com',
'password' => 'testpassword',
'salutation' => 'MrTest',
'title' => 'MScTest',
'firstname' => 'Testfirstname',
'lastname' => 'Testlastname',
'phonenumber' => 'testPhoneNumber',
'mobilenumber' => 'testMobileNumber',
]
);
$this->assertEquals($user->salutation, 'MrTest');
$this->assertEquals($user->title, 'MScTest');
$this->assertEquals($user->firstname, 'Testfirstname');
$this->assertEquals($user->lastname, 'Testlastname');
$this->assertEquals($user->phonenumber, 'testPhoneNumber');
$this->assertEquals($user->mobilenumber, 'testMobileNumber');
}
}
我得到以下信息:
1) UserTest::testUserCreation
Failed asserting that 'MrTest' matches expected null.
所有断言都返回 null。但是我检查了一下,数据库列存在。那么为什么该属性为空呢?
编辑:
如果我交换断言参数:
$this->assertEquals('MrTest', $this->salutation);
我明白这个:
ErrorException: Undefined property: UserTest::$salutation
将可填充覆盖移动到调用上方parent::__construct($attributes);
制作它:
public function __construct (array $attributes = array()) {
$this->fillable = array_merge ($this->fillable, array(
'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
));
parent::__construct($attributes);
}
这是因为主Model
类构造函数使用 fillable
数组,因此需要在调用构造函数之前对其进行设置。
[编辑] 更新了答案,仅包含所需的部分,并添加了一些解释为什么会这样