按条件多对多查询

有两个表,是多对多关系,分别叫account和resource,现在给定一组resource id,要求查出与每一个id都有关联的account,请问要怎么写。简化版数据表如下:

class Own(db.Model):
    owner_id = db.Column(db.Integer, db.ForeignKey('account.id'),
                     primary_key=True)
    owned_id = db.Column(db.Integer, db.ForeignKey('resource.id'),
                     primary_key=True)
    count = db.Column(db.Integer, default=1)

    owner = db.relationship('Account', back_populates='resources', lazy='joined')
    owned = db.relationship('Resource', back_populates='owners', lazy='joined')


class Account(db.Model):`
    id = db.Column(db.Integer, primary_key=True)
    resources = db.relationship('Own', back_populates='owner', cascade='all')`

class Resource(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    owners = db.relationship('Own', back_populates='owned', cascade='all')

————————
目前有个非常烂的想法,先用每个资源id在Own查出拥有此资源的owners,然后把这几组owners求交集得到用户

resource_ids = [1,2,3,4,5....]
account_objs = []

for resource_id in resource_ids:
    resource_obj = Resource.query.get(resource_id)
    if resource:
        account_objs.append(resource_obj.owners)

最后的account_objs 就是你要的结果,你试试这样,看行不行

要同时拥有资源1~5,这样查出来会包含很多只含其中部分资源的账户

好像目前求交集比较直接有效,虽然可能不是最优办法,大佬顺便看下我发的帖子的问题,指导一下 :joy:

@thawne
own表里group by,然后count,结果等于资源数的,就是你要的数据