在Eloquent中创建并保存具有填充关系的模型

时间:2019-04-01 16:00:07

标签: php orm eloquent eloquent--relationship

我有以下型号:

<?php

// namespaces removed for brevity

class User extends Model {

    /** {@inheritdoc} */
    protected $fillable = [
        'email',
        'password',
        'last_name',
        'first_name',
        'permissions',
    ];

    /** {@inheritdoc} */
    protected $hidden = ['password'];

    /**
     * @var string serve pra armazenar o nome da tabela desta entidade
     */
    protected $table = 'users';

    /**
     * @var bool deve criar campos para salvar datas da última alteração
     */
    public $timestamps = false;

    /**
     *
     */
    public function addRole(Role $role): void
    {
       $this->roles->put($role); // works in runtime but not persistence
       $this->roles->add($role); // can't remember what happens
       $this->roles()->attach($role); // User not persisted yet, so with no ID cannot construct relation
    }

    /**
     * Creates relationship with roles table.
     */
    public function roles(): BelongsToMany
    {
        // return $this->belongsToMany(Permission::class)->using(RolePermission::class);

        $pivotName = (new UserRole())->getTable();

        return $this->belongsToMany(Role::class, $pivotName)->withTimestamps();
    }
}

这些是我要执行的步骤:

  1. 创建雄辩的数据库模型实例new User
  2. 通过User::addRole(Role $role)向其添加角色(请参见方法代码和注释)。
  3. 通过User::save()保留用户实例。

用户存储在数据库中,而不是角色关系。

0 个答案:

没有答案