首页 > 解决方案 > Laravel 我添加了 morphmany SQLSTATE[42S22]: Column not found: 1054 Unknown column 'staff.staff_id' in 'field list'

问题描述

我正确存储了数据,但是当我尝试在编辑功能中获取数据时,它显示了这个错误

SQLSTATE [42S22]:未找到列:1054 '字段列表'中的未知列' staff.staff_id '(SQL:从内部连接中选择. * 、. usersas staffstaff_id.as pivot_staff_id、.as 、 .as 、 .as 、.as . = .其中.在 (2) 和. = App\Models\Investor)staffuser_idpivot_user_idstaffstaff_typepivot_staff_typestaffrolepivot_rolestaffcreated_atpivot_created_atstaffupdated_atpivot_updated_atusersstaffusersidstaffuser_idstaffstaff_idstaffstaff_type

//investor relationship
     public function staff()
    {
        return $this->morphToMany(User::class, 'staff')
                    ->withPivot(['role'])
                    ->withTimestamps();
    }
//user relationship

    public function investors()
    {
        return $this->morphedByMany(Investor::class, 'staff');
    }

标签: phplaravellaravel-5laravel-4

解决方案


您不遵循命名约定,因此您应该确定关系的foreign keyand "other key"

 public function staff()
{
    return $this->morphToMany(User::class, 'staff','name of table',
                                                   'foreignPivotKey','relatedPivotKey);
}

我不知道您的表格列名称,但在您的情况下可能如下所示:

public function staff()
{
    return $this->morphToMany(User::class, 'staff','staffabels',
                                                   'staffabel_id','staff_id')
                ->withPivot(['role'])
                ->withTimestamps();
}

public function investors()
{
    return $this->morphedByMany(Investor::class, 'staff','staffabels',
                                         'staff_id','staffable_id');
}

推荐阅读