首页 > 解决方案 > Laravel 5.6 - Eloquent 关系创建失败(类型错误)

问题描述

这是我目前得到的错误:

    Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() 
must be an instance of Illuminate\Database\Eloquent\Model, 
integer given, 
called in /home/sasha/Documents/OffProjects/vetnearme/vetnearme/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php on line 814

创建用户方法,我在这里调用giveRole ()方法:

protected function create(array $data)
    {
        $user = User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        // On registration user will be given the default role of user
        $user->giveRole();

        $verifyUser = VerifyUser::create([
            'user_id' => $user->id,
            'token'   => str_random(40)
        ]);

        Mail::to($user->email)->send(new VerifyMail($user));

        return $user;
    }

HasPermissionsTrait:

<?php

namespace App\App\Permissions;

use App\{Role, Permission};

/**
 *
 */
trait HasPermissionsTrait
{

    public function giveRole($role = 'user')
    {
        $role = \DB::table('roles')->where('name', '=', $role)->first();

        $this->roles()->saveMany([$role->id]);

        return $this;
    }

    public function givePermission(...$permissions)
    {
        $permissions = $this->getPermissions(\array_flatten($permissions));

        if($permissions === null)
            return $this;

        $this->permissions()->saveMany($permissions);

        return $this;
    }

    public function widrawPermission(...$permissions)
    {
        $permissions = $this->getPermissions(\array_flatten($permissions));

        $this->permissions()->detach($permissions);

        return $this;
    }

    public function updatePermissions(...$permissions)
    {
        $this->permissions()->detach();

        return $this->givePermission($permissions);
    }

    public function hasRole(...$roles)
    {
        foreach ($roles as $role) {

            if($this->roles->contains('name', $role))
                return true;

        }

        return false;
    }

    public function hasPermissionTo($permission)
    {
        return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
    }

    protected function hasPermission($permission)
    {
        return (bool) $this->permissions->where('name', $permission->name)->count();
    }

    protected function hasPermissionThroughRole($permission)
    {
        foreach ($permission->roles as $role) {
            if($this->role->contains($role))
                return true;
        }

        return false;
    }

    protected function getPermissions(array $permissions)
    {
        return Permissions::whereIn('name', $permissions)->get();
    }

    public function roles()
    {
         return $this->belongsToMany(Role::class, 'users_roles', 'user_id', 'role_id');
    }

    public function permissions()
    {
       return $this->belongsToMany(Permissions::class, 'users_permissions');
    }
}

好榜样:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function permissions()
    {
       return $this->belongsToMany(Permissions::class, 'roles_permissions');
    }

}

用户型号:

命名空间应用程序;

使用 App\App\Permissions\HasPermissionsTrait;

使用 Illuminate\Notifications\Notifiable;使用 Illuminate\Foundation\Auth\User 作为 Authenticatable;

class User extends Authenticatable
{
    use Notifiable, HasPermissionsTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function clinic()
    {
       return $this->hasOne(Clinic::class, 'owner_id');
    }

    public function files()
    {
       return $this->hasMany('App/Media');
    }

    public function verifyUser()
    {
        return $this->hasOne('App\VerifyUser');
    }

}

我在这里做错了什么?

标签: laravellaravel-5

解决方案


您是否尝试过传入角色模型而不是 id?另外,在单独的注释中,看起来您最好只是调用save,因为您实际上并没有在这种情况下使用数组。

trait HasPermissionsTrait
{

    public function giveRole($role = 'user')
    {
        $role = \DB::table('roles')->where('name', '=', $role)->first();

        $this->roles()->saveMany([$role]);

        return $this;
    }

}

saveMany调用保存:

public function saveMany($models, array $joinings = [])
{
    foreach ($models as $key => $model) {
        $this->save($model, (array) Arr::get($joinings, $key), false);
    }
    $this->touchIfTouching();
    return $models;
}

并且save有类型转换Model,而不是 int:

/**
 * Save a new model and attach it to the parent model.
 *
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @param  array  $joining
 * @param  bool   $touch
 * @return \Illuminate\Database\Eloquent\Model
 */
public function save(Model $model, array $joining = [], $touch = true)
{
    $model->save(['touch' => false]);
    $this->attach($model->getKey(), $joining, $touch);
    return $model;
}

推荐阅读