这里使用到三张表,一张是用户(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;
}