Laravel模型继承 [英] Laravel model inheritance

查看:144
本文介绍了Laravel模型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel的Toddish/Verify库,因为它包含了我项目的99%的需求.我只需要添加一些字段即可.

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

我明白了:

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.

我在做什么错了?

推荐答案

问题是您要覆盖我认为的Eloquent构造函数,因此永远不会传递值.

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

更改__construct如下所示.

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

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

Model::create方法实际上将创建模型的新实例,并将数组传递给__construct.您要重写此设置,并阻止它传递信息.

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.

这篇关于Laravel模型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆