Laravel model inheritance

一曲冷凌霜 提交于 2019-12-11 05:34:29

问题


I am using the Toddish/Verify library for Laravel as it includes 99% of what I need for my project. All I need is to add some fields.

I have added them in a migration, and I want to add them also to mass creation:

use Toddish\Verify\Models\User as VerifyUser;

class User extends VerifyUser
{
    public function __construct () {
        array_merge ($this->fillable, array(
            'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
        ));
    }
}

However, when I run my creation test:

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');
}

I get this:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 users.username may not be NULL (SQL: insert into "users" ("updated_at", "created_at") values (2014-03-03 09:57:41, 2014-03-03 09:57:41))

in all tests that involve user creation, as if it had forgotten about the parents attributes when saving the model.

What am I doing wrong?


回答1:


The problem is that you're overriding what I assume is the Eloquent constructor, so the values are never getting passed.

Change __construct to look like the following.

public function __construct(array $attributes = array())
{
    parent::__construct($attributes);

    array_merge ($this->fillable, array(
        'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
    ));
}

The Model::create method will actually create a new instance of the model and pass the array into the __construct. You're overriding this and preventing it from passing the information through.

Note If you decide to override core methods like you've done here, always check inheritance and make sure you aren't breaking anything.



来源:https://stackoverflow.com/questions/22143985/laravel-model-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!