tp6关联方法返回relation实例而非query,需用get()/all()触发查询,with()不支持链式where须用闭包,自动注入改为惰性加载,join()被withjoin()替代,软删除行为默认继承主模型。

ThinkPHP 6.x 关联方法名和返回值类型变了
TP6 把 belongsTo、hasOne 等关联定义方法的返回类型从 Query 改成了 Relation 实例,直接调用 select() 或 find() 会报错:Call to undefined method think\model\relation\BelongsTo::select()。
老代码里常见这种写法:$user->profile()->select(),TP6 必须改成先取关联模型再查,比如:$user->profile()->withAttr(...)->select() 或拆成两步:$profile = $user->getProfile(); $profile->toArray();。
- TP5.1 的关联方法返回的是
Query对象,能链式调用查询方法 - TP6+ 返回的是
Relation对象,要通过get()、all()、find()等方法触发查询 -
with()预载入在 TP6 中仍可用,但内部实现已重构,不支持对关联对象二次调用where()—— 得用闭包条件:with(['profile' => function ($q) { $q->where('status', 1); }])
TP5 和 TP6 的关联属性自动注入行为不一致
TP5 默认把关联结果以属性形式挂到主模型上(如 $user->profile),TP6 默认只在显式调用 getRelation() 或访问器触发时才加载,且不会自动赋值给属性 —— 这意味着模板里直接写 {$user.profile.name} 在 TP6 可能报 Trying to get property 'name' of non-object。
解决方式不是硬加判空,而是统一用访问器或预载入兜底:
- 在模型中定义
getProfileAttr访问器,内部调用$this->getProfile()并做空值处理 - 批量查询时强制用
with('profile'),确保关联数据已加载 - 避免在模板中直接链式访问深层属性,改用
{$user.profile?.name}(PHP 8+)或{$user.profile ? $user.profile.name : ''}
TP6 的 together() 和 withJoin() 不兼容 TP5 的 join() 关联写法
TP5 允许在关联定义里写 join() 方法模拟 left join 查询,TP6 废除了这个能力,改用 withJoin()(需开启 think-model 扩展)或原生 alias()+join() 组合。
典型错误是把 TP5 的关联定义直接搬过去,比如:
public function profile()
{
return $this->hasOne(Profile::class)->join('profile', 'user.id=profile.user_id');
}
TP6 会忽略 join() 调用,还可能报 Method join does not exist。正确做法是:
- 简单场景:用
withJoin('profile')替代with('profile'),前提是模型已定义标准关联 - 复杂条件:不用
withJoin,改写为原生查询:UserModel::alias('u')->join('profile p', 'u.id=p.user_id')->field('u.*, p.nickname')->select() -
together()是 TP6 新增方法,用于合并主表与关联表字段(类似 SQL SELECT * FROM a JOIN b),但它不支持嵌套关联,也不走模型事件,慎用于需要自动转换/过滤的字段
关联软删除字段在 TP5 和 TP6 中默认行为不同
TP5 的关联查询默认忽略软删除(即不自动加 delete_time IS NULL),TP6 则默认继承主模型的软删除状态 —— 如果主模型启用了软删除,关联模型没启用,TP6 会把关联表也加上 delete_time IS NULL 条件,导致查不到数据。
这不是 bug,是设计变更,但容易被忽略:
- 检查关联模型是否也用了
SoftDeletetrait;没用的话,在关联定义里手动关闭:return $this->hasOne(Profile::class)->withoutGlobalScope(SoftDelete::class); - 如果主模型没软删除而关联模型有,TP6 默认也不会加条件,此时需显式启用:
->withTrashed()或->onlyTrashed() - TP5 中
withTrashed()是关联方法上的,TP6 中它属于Relation实例方法,必须写在getProfile()后面,不能写在profile()定义里
跨版本适配最麻烦的不是语法,是这些默认行为的“静默切换”——没报错,但数据少了一半,得盯着 SQL 日志才能发现。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











