我有一个模型,它继承自Toddish \ Verify Laravel包(https://github.com/Toddish/Verify-L4/blob/master/src/Toddish/Verify/Models/User.php)
我想要做的就是添加一些属性:
use Toddish\Verify\Models\User 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。但我检查了数据库列。那么为什么该属性为null?
编辑:
如果我交换断言参数:
$this->assertEquals('MrTest', $this->salutation);
我明白了:
ErrorException: Undefined property: UserTest::$salutation
答案 0 :(得分:2)
您需要将可填写覆盖移动到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
数组,因此需要在调用构造函数之前设置它。
[编辑] 更新了答案,仅包含所需的部分,并添加了一些解释原因的原因