一、文档
https://learnku.com/docs/laravel/6.x/eloquent-relationships/5177#d9e83d
二、实例
1、表结构
admin表
role表
auth表
role_auth表
2、模型
admin.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2023/11/11 0011 * Time: 9:50 */ namespace App\Models; use Illuminate\Database\Eloquent\Model; class Admin extends Model { protected $table = 'admins'; public function role() { return $this->belongsTo(Role::class, 'role_id', 'id'); } }
role.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2023/11/11 0011 * Time: 9:51 */ namespace App\Models; use Illuminate\Database\Eloquent\Model; class Role extends Model { protected $table = 'roles'; public function admins() { return $this->hasMany(Admin::class, 'role_id', 'id'); } public function auths() { return $this->belongsToMany(Auth::class, 'role_auths', 'role_id', 'auth_id'); } }
auth.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2023/11/11 0011 * Time: 10:18 */ namespace App\Models; use Illuminate\Database\Eloquent\Model; class Auth extends Model { protected $table = 'auths'; public function roles() { return $this->belongsToMany(Role::class, 'role_auths', 'auth_id', 'role_id'); } }
3、获取数据
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2023/11/11 0011 * Time: 9:58 */ namespace App\Services; use App\Models\Role; class RoleService { /** * @param $id * @return array */ public function getAdminsAndAuthByRoleId($id) { return Role::with('admins')->with('auths')->where('id', '=', $id)->first()->toArray(); } }
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2023/11/11 0011 * Time: 9:57 */ namespace App\Services; use App\Models\Admin; class AdminService { /** * 获取管理员详细信息 * @param $id * @return array */ public function getAdminInfoById($id) { return Admin::with('role')->where('id', '=', $id)->first()->toArray(); } }
4、数据结果
$admin = $adminService->getAdminInfoById(1); var_dump($admin);
$role = $roleService->getAdminsAndAuthByRoleId(2); var_dump($role);
标签:框架,auths,auth,class,admin,ORM,role,Lumen,id From: https://www.cnblogs.com/yang-2018/p/17825646.html