How to Perform Join Queries in ThinkPHP: Native SQL, join() and table() Methods
This article demonstrates how to execute multi-table join queries in ThinkPHP using native SQL, the join() method, and the table() method, providing clear code examples for each approach, including aliasing, ordering, and pagination details.
ThinkPHP supports multi-table join queries through three main approaches: writing raw SQL, using the join() method, and using the table() method. The following examples illustrate each technique.
1. Native query example:
<code>$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);
</code>2. join() method example:
<code>$user = new Model('user');
$list = $user->join('RIGHT JOIN user_profile ON user_stats.id = user_profile.typeid');
</code>3. Complex join using multiple join() calls:
<code>$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 表的 user_id 等于 $b_user 表的 b_userid;
// $c_user 表的 c_userid 等于 $b_user 表的 b_userid;
</code>4. table() method example:
<code>$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();
</code>These snippets show how to perform join queries, set aliases, apply conditions, select specific fields, order results, and limit output within ThinkPHP.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.