top-think / top-think/think-orm

多对多模型中间表pivot提示外键不存在

Open
#531 1 comment 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

vendor/topthink/think-orm/src/model/relation/BelongsToMany.php
方法eagerlyManyToMany拿到的中间表数据存放在了key为pivot的数组里,并且模型getData方法获取不到,这个就会导致后面的matchPivot方法报不存在中间表外键的错误,$list对应的查询sql打印出来是:SELECT yoshop_spec_value.*,pivot.id AS pivot__id,pivot.goods_id AS pivot__goods_id,pivot.spec_id AS pivot__spec_id,pivot.spec_value_id AS pivot__spec_value_id,pivot.wxapp_id AS pivot__wxapp_id,pivot.create_time AS pivot__create_time,pivot.update_time AS pivot__update_time FROM yoshop_spec_value INNER JOIN yoshop_goods_spec_rel pivot ON pivot.spec_value_id=yoshop_spec_value.spec_value_id WHERE pivot.goods_id = '670' ORDER BY id ASC

image image image

上一步的基础查询baseQuery方法里返回的是正常的,这里的$result返回的中间表数据是以pivot__开头的字段存放的,并且模型的getData方法可以拿到
image

尝试后发现,多对多关联的时候我加上排序导致的,如果去掉排序,这个结果就正常了
return $this->belongsToMany(SpecValue::class, GoodsSpecRel::class)
->order(['id' => 'asc']);

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 vendor/topthink/think-orm/src/model/relation/BelongsToMany.php and trace eagerlyManyToMany, baseQuery, and matchPivot. Reproduce the many-to-many query using the shown relation and order(['id' => 'asc']), then compare the pivot__ fields returned with and without ordering. Done means the ordered relation no longer reports a missing intermediate-table foreign key.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
database
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.