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表中的全部数据。

相关推荐
Eternal-Student13 分钟前
everyday_question dq20240731
开发语言·arm开发·php
zhangphil1 小时前
Windows环境Apache httpd 2.4 web服务器加载PHP8:Hello,world!
php·apache·httpd
500了5 小时前
Kotlin基本知识
android·开发语言·kotlin
人工智能的苟富贵6 小时前
Android Debug Bridge(ADB)完全指南
android·adb
芒果作者10 小时前
dcatadmin 自定义登录页面
php
小雨cc5566ru11 小时前
uniapp+Android面向网络学习的时间管理工具软件 微信小程序
android·微信小程序·uni-app
bianshaopeng12 小时前
android 原生加载pdf
android·pdf
hhzz12 小时前
Linux Shell编程快速入门以及案例(Linux一键批量启动、停止、重启Jar包Shell脚本)
android·linux·jar
火红的小辣椒13 小时前
XSS基础
android·web安全
酷酷-14 小时前
彩虹易支付最新版源码及安装教程(修复BUG+新增加订单投诉功能)
html·php·bug