Skip to content

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

@lscar

Description

@lscar

问题描述
在 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions