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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web项目开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值