thinkphp 关联模型 一对多关联 主副表查询

一对多关联查询

namespace app\model;

use think\Model;

class Users extends Model
{
    // 模型中定义一对多关系的方法 用于建立当前模型与另一个模型之间的关系, 例如: 当前数据表对应的外键表
    // profile 自定义方法名  Profile::class 关联数据表的模型文件类名
    public function profile()
    {
        // hasMany模式 一对多关系查询 在主表里面 查询 副表的数据
        // 主表关联副表 hasMany('关联模型名', ['关联外键','主键']) [users_id, id]
        // 关联模型名 必须的: 关联模型名或者类名 Profile::class
        // 外键:默认的外键是当前模型名(不含命名空间)+_id, 例如: 当前模型名是Users, 默认的外键是users_id
        // 主键:主键是当前模型的主键, 默认会自动获取也可以指定传入
        return $this->hasMany(Profile::class, 'users_id', 'id');
    }
}

使用的地方 类里
<?php

namespace app\controller;

use app\BaseController;
use app\model\Profile;
use app\model\Users;


class Login extends  BaseController
{
    public function index()
    {
        //  一对多关系查询
        // 查询副表的数据
        // $user = Users::find(1);
        // return $user->profile;
        // $data = $user->profile->where('id', '>', 2);
        // $data = $user->profile()->where('id', '>', 3)->select();

        // 查询主表的数据
        // has() 查询副表大于2条的主表数据 返回对应的主表数据
        // $data =  Users::has('profile', '>', 2)->select();

        // hasWhere() 查询副表的数据 返回对应的主表数据
        // profile 关联的 副表模型名
        // $data = Users::hasWhere('profile', ['id' => 1])->select();
        // 闭包形式
        // $data = Users::hasWhere('profile', function($query) {
        //     return $query->where('id','>',10);
        // })->select();

        // 新增
        // $data = Users::find(1);
        // $data->Profile()->save(['hobby' => 'thinkphp']);

        // 删除  删除的是主表 id为1的 和 id为1副表关联的数据
        $users = Users::with('profile')->find(1);
        $users->together(['profile'])->delete();

        return $users;
    }
  }

posted on   完美前端  阅读(255)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2021-01-23 初始化css

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

点击右上角即可分享
微信分享提示