Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一对多,怎么update子属性 #1670

Open
overlbjn opened this issue Apr 23, 2021 · 4 comments
Open

一对多,怎么update子属性 #1670

overlbjn opened this issue Apr 23, 2021 · 4 comments

Comments

@overlbjn
Copy link

DESC

model A 和 model B是一对多关系
await think.model('A').where({ status: 2 }).setRelation('B', {
type: think.Model.HAS_MANY,
where: { status: 1 },
}).select()
await think.model('A').where({ status: 2 }).setRelation('B', {
type: think.Model.HAS_MANY,
where: { status: 1 },
}).update({ status: 2, B: { status: 3 } });

结果A的子B可以全部查到,A的status可以修改成功但是A的子B并没有更改成功,请问怎么才能把符合条件的A的子B的status都改成1?

@lizheming
Copy link
Contributor

lizheming commented Apr 24, 2021

看了一下代码,目前更新的话需要把需要更新的 primary key 值也传入才行,目前你的这种情况应该不太试用。目前建议你在这种情况下暂时可以选择使用多条语句进行更新。

const data = await this.model('A').where({status: 2}).select();
const ids = data.map(({id}) => id);
await this.model('A').where({id: ['IN', ids]}).update({status: 2});
await this.model('B').where({A_id: ['IN', ids]}).update({status: 3});

@overlbjn
Copy link
Author

看了一下代码,目前更新的话需要把需要更新的 primary key 值也传入才行,目前你的这种情况应该不太试用。目前建议你在这种情况下暂时可以选择使用多条语句进行更新。

const data = await this.model('A').where({status: 2}).select();
const ids = data.map(({id}) => id);
await this.model('A').where({id: ['IN', ids]}).update({status: 2});
await this.model('B').where({A_id: ['IN', ids]}).update({status: 3});

好的,多谢,因为B是根据A的查询条件和B的筛选条件查出来的,所以id不确定,后续会更新吗,把查出来的B传出下一层进行update

@lizheming
Copy link
Contributor

可能不是很好加,这里主要是考虑了一条数据的更新,对应关联数据的话可能是更新,也可能是添加操作。我看现在的逻辑里是通过 primary key 来判断是否是对关联数据的更新的。如果缺少 primary key 的话,可能这个逻辑就不好判断了。https://github.com/thinkjs/think-model/blob/master/src/relation/has_many.js#L32-L50

当然如果有更好的建议可以提出,我们沟通下看看怎么处理一下。

@gtfd333
Copy link

gtfd333 commented Apr 25, 2021

考虑手工处理下吧,几大语言的orm框架都不能很好的处理这个问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants