hyperf 多对多关联模型

这里使用到三张表,一张是用户(users),一张是角色(roles),一张是用户角色关联表(users_roles),
首先创建用户模型、角色模型

php bin/hyperf.php gen:model users
php bin/hyperf.php gen:model roles

users模型

<?php
declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
/**
 * users模型 
 */
class users extends Model
{
    protected $connection = 'sso';
    protected $primaryKey = 'ID';//因为我表里的主键是大写的,所以这里我用大写,否则使用关联模型会出问题

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'users';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];

    /*多对多建立关系*/
    public function roles()
    {
        return $this->belongsToMany(roles::class,'users_roles','userId','roleId');
    }
}

roles模型

<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
/**
 * roles模型
 */
class roles extends Model
{
    protected $connection = 'sso';
    protected $primaryKey = 'ID';
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'roles';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];

    public function users()
    {
        return $this->belongsToMany(users::class,'users_roles','roleId','userId');
    }
}
  • 1、其中users_roles是我关联表的表名

  • 2、belongsToMany方法中,第一个参数,参数的与之关联的表模型;第二个参数是两个表的关联表(中间表);第三个参数是定义此关联的模型在连接表里的外键名;第四个参数是另一个模型在连接表里的外键名;

分页数据

public function paginate()
{
    $data = Db::table('hlyun_sso_users')->paginate(10);
    return $data;
}

相关推荐

  1. hyperf 关联模型

    2024-05-26 03:08:40       10 阅读
  2. 数据库(关系关联查询)

    2024-05-26 03:08:40       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-26 03:08:40       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-26 03:08:40       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-26 03:08:40       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-26 03:08:40       20 阅读

热门阅读

  1. 云存储与云计算详解

    2024-05-26 03:08:40       11 阅读
  2. 使用两块ESP8266实现ESP-NOW通信

    2024-05-26 03:08:40       10 阅读
  3. Git管理

    2024-05-26 03:08:40       11 阅读
  4. Cisco ASA防火墙抓包命令Capture

    2024-05-26 03:08:40       9 阅读
  5. vue3项目中新增修改时使用nextTick时遇到的问题

    2024-05-26 03:08:40       9 阅读
  6. Flutter 中的 CupertinoTabBar 小部件:全面指南

    2024-05-26 03:08:40       13 阅读
  7. echarts 大数据量 数据造成卡顿处理

    2024-05-26 03:08:40       13 阅读
  8. Python库之Scrapy的高级用法深度解析

    2024-05-26 03:08:40       13 阅读
  9. Cisco Catalyst 9000 9200 9300 9400 IOS software upgrade

    2024-05-26 03:08:40       13 阅读