Laravel Eloquent create null field

2019-09-03 03:29发布

class Product extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];
    public $timestamps = true;
    protected $fillable = ['name'];
    protected $connection = 'pos';

    public function __construct()
    {
        config(['database.connections.pos.database' => 'pos_1']);
        parent::__construct();
    }
}

Product::create(['name' => 'Snack']);

on my db id=1, name=null, created_at='2016-06-26 18:30:24', updated_at='2016-06-26 18:30:24', deleted_at=null

Why name=null?


Update post

works when I use

$p = new Product();
$p->name = 'Snack';
$p->save();

but why Product::create(['name' => 'Snack']); fill as null ?


Update post(solved)

ah I missing pass array as parameter on that constructor.

        public function __construct(array $attributes)
        {
            config(['database.connections.pos.database' => 'pos_1']);
            parent::__construct($attributes);
        }

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-03 04:00

Probably the reason is that you again don't run parent constructor.

Instead of:

public function __construct()
{
    config(['database.connections.pos.database' => 'pos_1']);
}

you should use:

public function __construct()
{
    config(['database.connections.pos.database' => 'pos_1']);
    parent::__construct();
}

Be aware that for your Eloquent Model you have also connection property, so you could probably set also name of database connection.

查看更多
登录 后发表回答