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; } }
分类:
php
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
2021-01-23 初始化css