php 两表关联查询,Thinkphp连多表查询,关联2个或多个字段

tp连表查询的问题:a表的user_id关联b表的id,a表的race_id关联c表的race_id,a表的race_id和user_id关联d表的race_id和user_id。4表关联,a表和d表还是关联2个字段。

tp作为国内最优秀的php框架,提供了一种简单的join来关联表。下面是示例代码

php 复制代码
$where = array(

'a.id'=>1,

'b.id'=>1,

);

$result = $this ->join('LEFT JOIN b ON a.user_id = b.id')

->join('LEFT JOIN c ON a.race_id = c.race_id')

->join('LEFT JOIN d a.race_id = d.race_id AND a.user_id = d.user_id')

->where($where)

->select();

当然,这只是一个小例子,where条件中的a.id代表a表中的id字段,b.id同理。 LEFT JOIN就是php中连表查询中常用的,join()可以一直加下去(只要表名对应的字段存在,即a.user_id = b.id,a表中必须有user_id,b表中必须有id,条件才能成立)

大家知道,连表有时候会有重复字段,我的解决方法是使用thinkphp中的field()。例如:

php 复制代码
$result = $this ->join('LEFT JOIN b ON a.user_id = b.id')
->join('LEFT JOIN c ON a.race_id = c.race_id')
->join('LEFT JOIN d a.race_id = d.race_id AND a.user_id = d.user_id')
->where($where)
-> field('a.name as a_name , b.*,c.&,d.*')
->select();

a.name as a_name意思就是把a表中的name字段换成a_name去显示出来。b.*代表的是取b表中的全部数据。

相关推荐
Ether IC Verifier7 分钟前
OSI网络七层协议详细介绍
服务器·网络·网络协议·计算机网络·php·dpu
这儿有一堆花41 分钟前
住宅代理(Residential Proxy)技术指南
开发语言·数据库·php
niucloud-admin2 小时前
PHP V6 单商户常见问题——升级提示mkdir()处理方案
php
李艺为3 小时前
Fake Device Test作假屏幕分辨率分析
android·java
zh_xuan3 小时前
github远程library仓库升级
android·github
峥嵘life3 小时前
Android蓝牙停用绝对音量原理
android
计算机安禾4 小时前
【Linux从入门到精通】第37篇:NFS网络文件系统——无状态的数据共享
linux·网络·php
2401_873479405 小时前
深度解析IP查询工具与普通IP库的核心区别:选型指南与业务场景对照
网络协议·tcp/ip·php
张晓℡¹⁸⁰³⁷¹⁸²⁵⁵⁸5 小时前
海外盲盒APP玩法集合,海外盲盒多国语言
小程序·php