我一直在try 创建一个简单的用户管理系统,但在查询关系时遇到了障碍.例如,我有usersroles,每当我试图对所有用户及其角色进行查询时,都会出现一个错误.标题中的那个只是我遇到的最新的一个.

我的用户和角色模型如下所示:

class Role extends Model
{
    public function users()
    {
        $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
    }
}

class User extends Model
{
    public function roles()
    {
        $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
    }
}

我的这两者之间多对多关系的迁移表如下所示:

public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable(); //fk => users
            $table->integer('role_id')->unsigned()->nullable(); //fk => roles

            $table->foreign('fk_user_role')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('fk_role_user')->references('id')->on('roles')->onDelete('cascade');
        });
    }

然后我try 在控制器中获取所有记录及其关系:

public function index()
{
    $users = User::with('roles')->get();

    return $users;
}

所以我需要另一双眼睛来告诉我我错过了什么?

推荐答案

在定义关系的方法中缺少return条语句.它们需要返回关系定义.

代替

public function roles()
{
    $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}

使用

public function roles()
{
    return $this->belongsToMany('\App\Role', 'role_user', 'user_id', 'role_id');
}

Php相关问答推荐

根据用户ID禁用WooCommerce checkout 下单按钮

如何使用URL链接(mdl)切换选项卡

PHP如何将ARRAY_MAP与Reset()配合使用

如果WooCommerce中存在特定的运输方式,则隐藏其他运输方式

PHP原始数据读取引发max_input_vars错误

如何在Foreach语句中使用php和li按降序排序?

在PHP中循环访问多维数组,并按组显示内容

如何在Livewire 3 Form类中做依赖注入?

如何在UML类图中可视化变量引用数组

WooCommerce中基于用户角色的不同产品差价

SFTP在PHP(phpseclib3\Net\SFTP)-过滤目录列表结果服务器端可能吗?类似于psftp中的LS命令?

如何在PHP中根据会话将用户重定向到不同的页面?

防止 WooCommerce 在前端加载全尺寸图像

.htaccess 重写规则问题

标签打印机的 CSS

WooCommerce订单支付页面上的附加支付订单按钮

同一页面上多个组件的 Livewire 分页问题

Laravel 8:会话不适用

如何使用属性创建属性预设?

如何为多个表的id列设置不同的值