本文主要是介绍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模型
<?phpdeclare (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;
}
这篇关于hyperf 多对多关联模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!