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.

php Courses
php Courses
php Courses
How to Perform Join Queries in ThinkPHP: Native SQL, join() and table() Methods

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:

$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. join() method example:

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

3. Complex join using multiple join() calls:

$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;

4. table() method example:

$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();

These snippets show how to perform join queries, set aliases, apply conditions, select specific fields, order results, and limit output within ThinkPHP.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ThinkPHPJoin Query
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.