top-think / top-think/think-orm

Model 设置 suffix 后,会错误地影响 join 方法中的关联表名

Open
#841 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
437
Forks
188
PR merge metrics
No merged PRs in 30d

Description

问题描述
在 topthink/think-orm v3.0.34 版本中,当对模型实例调用 suffix() 设置表后缀后,通过 join() 方法关联的其他表也会被自动加上相同的后缀。这导致如果关联表本身不存在该后缀(未分表),生成的 SQL 将会因找不到表而报错。

源码src/db/concern/JoinAndViewQuery.phpgetJoinTable方法

// 现有的逻辑
if ($this->prefix && !str_contains($table, '.') && !str_starts_with($table, $this->prefix)) {
    $table = $this->prefix . Str::snake($table) . $this->suffix;
}

复现代码

// 表前缀 bp_order_
// Lists 模型对应表 bp_order_lists
// project 表名(无后缀)

$find = Lists::suffix('_2025')
    ->alias('a')
    ->where('a.order_sn', '=', '10240821140702897732885')
    ->join('project b', 'a.id=b.order_id')
    ->field('a.order_sn, a.server_id, b.project_name')
    ->fetchSql()
    ->select();

dump($find);

预期结果join 方法中的表名应该保持原样,除非显式指定后缀

SELECT `a`.`order_sn`, `a`.`server_id`, `b`.`project_name` 
FROM `bp_order_lists_2025` `a` 
INNER JOIN `bp_order_project` `b` ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`order_sn` = '10240821140702897732885'

实际结果join 中的 project 表被错误地加上了主表的后缀 _2025

SELECT `a`.`order_sn`, `a`.`server_id`, `b`.`project_name` 
FROM `bp_order_lists_2025` `a` 
INNER JOIN `bp_order_project_2025` `b` ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`order_sn` = '10240821140702897732885'

环境信息

  • PHP Version: 8.2
  • Think-ORM Version: v3.0.34

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/db/concern/JoinAndViewQuery.php at getJoinTable and reproduce the issue with the provided Lists::suffix(), join('project b', ...), and fetchSql() example. Check the generated SQL against the expected query: the main table should retain _2025 while the joined project table should not inherit that suffix unless explicitly specified.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
database
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.