top-think / think-orm

Think ORM——the PHP Database&ORM Framework
Apache License 2.0
416 stars 173 forks source link

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

Open iimeepo opened 6 months ago

iimeepo commented 6 months ago

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']);

flowerwOw0316 commented 1 month ago

怪不得我说有的查询用with不行,最后去append反而又行了,BelongsToMany问题 +1