Common Methods of ThinkPHP Multi table Joint Query

  • 2021-07-06 10:14:28
  • OfStack

The associated query in ThinkPHP (that is, a multi-table union query) can use the table () method or the join method, as shown in the following example:

1. Examples of native queries:


$Model = new Model();
$sql = 'select a.id,a.title,b.content from think_test1 as a, think_test2 as b where a.id=b.id '.$map.' order by a.id '.$sort.' limit '.$p->firstRow.','.$p->listRows;
$voList = $Model->query($sql);

2. Example of the join () method:


$user = new Model('user');
$list = $user->join('RIGHT JOIN user_profile ON user_stats.id = user_profile.typeid' );

Method of Thinkphp using join join table query


$user = M('user');
$b_user = M('b_user');
$c_user = M('c_user');
$list = $user->alias('user')->where('user.user_type=1')
  ->join('b_user as b on b.b_userid = user.user_id')
  ->join('c_user as c on c.c_userid = b.b_userid')
  ->order('b.user_time')
  ->select();

user_id of $user table is equal to b_userid of $b_user table;

c_userid of $c_user table is equal to b_userid of $b_user table;

3. Example of the table () method:


$list = $user->table('user_status stats, user_profile profile')->where('stats.id = profile.typeid')->field('stats.id as id, stats.display as display, profile.title as title,profile.content as content')->order('stats.id desc' )->select();

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "smarty Template Introduction Basic Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: