Lumen框架 之ORM


一、文档

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);

 

如果你感觉有收获,欢迎给我打赏 ———— 以激励我输出更多优质内容,联系QQ:2575404985
        
posted @   样子2018  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
历史上的今天:
2021-11-11 PHP 之判断是否为移动端
2019-11-11 Tkinter 之ProgressBar进度条标签
点击右上角即可分享
微信分享提示

目录导航

一、文档
二、实例
1、表结构
2、模型
3、获取数据
4、数据结果