How to implement MySQL multi-table joint query in ThinkPHP: First instantiate the model; then use the table() method or join() method to query, for example: [table('sp_user as t1, sp_dept as t2')].
The content of this article is about how to implement MySQL multi-table joint query (pictures and texts) in ThinkPHP. It has certain reference value. Friends in need can refer to it, I hope it will be helpful to you.
Recommended related video tutorials: "mysql tutorial", "PHP tutorial"
Create two tables as shown in the figure:
sp_user table:
sp_dept table:
Purpose: Query the name of the department to which it belongs through the dept_id of sp_user, that is, the name in sp_dept.
Native sq method one:
select t1.*,t2.name as deptname from sp_user as t1,sp_dept as t2 where t1.dept_id = t2.id;
Native sq method two:
select t1.*,t2.name as deptname from sp_user as t1 left join sp_dept as t2 on t1.dept_id = t2.id;
The result is the same:
corresponds to ThinkPHP, there are two types The methods table and join are as follows:
//多表联查(table) public function test18() { //实例化模型 $model = M(); //查询 $result =$model->field('t1.*, t2.name as deptname')->table('sp_user as t1, sp_dept as t2') ->where('t1.dept_id = t2.id')->select(); dump($result); } //多表联查(join) public function test19() { //实例化模型 $model = M('User'); //查询 $result = $model->field('t1.*, t2.name as deptname')->alias('t1') ->join('left join sp_dept as t2 on t1.dept_id = t2.id')->select(); dump($result); }
The test results are the same:
## In summary: ThinkPHP performs multi-table joint query It can be realized through table method and join method respectively. Test environment ThinkPHP3.2.3, table prefix sp_ Related recommendations:How about 2 tables Related query (thinkphp)
Related query example in ThinkPHP, ThinkPHP related example
The above is the detailed content of How to implement MySQL multi-table joint query in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!