0

我在我的 laravel 项目中使用 laravel-admin (https://laravel-admin.org) 。我希望在用户的用户管理面板角色名称上显示。但我收到错误消息:

SQLSTATE[42703]:未定义列:7 错误:列 users_roles.role___id 不存在第 1 行:...les" 在 "roles" 上内连接 "users_roles"。"__id" = "users_rol... ^ (SQL: select "roles".*, "users_roles"."user___id" as "pivot_user___id", "users_roles"."role___id" as "pivot_role___id" from "roles" 内部连接 ​​"users_roles" on "roles"。"__id" = "users_roles" ."role___id" where "users_roles"."user___id" in (1, 2, 3))

这是我的类和控制器:

用户.php:


namespace App\Models;


/**
 * Class User
 * @package App\Models
 *
 * @property integer $__id
 * @property string $email
 * @property string $password
 * @property string|null $firstname
 * @property string|null $lastname
 * @property \DateTime|null $visited_at
 * @property string|null $phone
 * @property string|null $avatar
 * @property string|null $remember_token
 * @property \DateTime $created_at
 * @property \DateTime $updated_at
 */
class User extends Authenticatable
{
    use Notifiable;

    protected $primaryKey = '__id';

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

Role.php:
<?php

namespace App\Models;

/**
 * Class Role
 * @package App\Models
 *
 * @property integer $__id
 * @property string $key
 * @property string $name
 */
class Role extends Model
{
    protected $primaryKey = '__id';

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class,'users_roles');
    }
}

UserController.php:

<?php
namespace App\Admin\Controllers;

class UserController extends AdminController
{
    protected $title = 'User';

    protected function grid()
    {
        $grid = new Grid(new User());

        $grid->column('__id', __('  id'));
        $grid->column('email', __('Email'));
        $grid->column('password', __('Password'));
        $grid->column('firstname', __('Firstname'));
        $grid->column('lastname', __('Lastname'));

        $grid->roles()->display(function($roles) {

            $roles = array_map(function ($role) {
                return "<span class='label label-success'>{$role['name']}</span>";
            }, $roles);

            return join('&nbsp;', $roles);
        });
        .......
         .........
}

Pivot table users_roles:

create table if not exists users_roles
(
    __user_id bigint not null
        constraint users_roles___user_id_foreign
            references users,
    __role_id bigint not null
        constraint users_roles___role_id_foreign
            references roles,
    become_at timestamp(0) not null,
    left_at timestamp(0)
);

我注意到数据透视表的 __role_id 列的名称在查询中被转换为 role___id(因为错误消息告诉我:“错误:列 users_roles.role___id”)。如何解决这个问题呢?

4

1 回答 1

0

我不得不做一些更正:

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

并且错误消息消失了。

于 2020-06-01T14:53:13.743 回答