如何通过对相关车型的条件来过滤? [英] How to filter by conditions for associated models?

查看:123
本文介绍了如何通过对相关车型的条件来过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对用户和联系人一belongsToMany关联。

I have a belongsToMany association on Users and Contacts.

我想找个给定用户的联系人。
我需要这样的东西。

I would like to find the Contacts of the given User. I would need something like

$this->Contacts->find()->contain(['Users' => ['Users.id' => 1]]);

菜谱谈到给予遏制,自定义查找程序方法,并通过关联键唱歌的条件,但我没有找到如何把这些结合在一起。

The cookbook speaks about giving conditions to contain, custom finder methods and sing through association key, but I did not find out how to put these together.

推荐答案

在从联系人表,那么你正在寻找的是查询::匹配()或查询查询:: innerJoinWith(),不(只)查询::包括()

Use Query::matching() or Query::innerJoinWith()

When querying from the Contacts table, then what you are looking for is Query::matching() or Query::innerJoinWith(), not (only) Query::contain().

请参阅食谱>数据库访问和放大器; ORM>查询生成器>由Associated数据过滤

下面是一个使用你的表的例子:

Here's an example using your tables:

$this->Contacts
    ->find()
    ->matching('Users', function(\Cake\ORM\Query $q) {
        return $q->where(['Users.id' => 1]);
    });

这会自动添加所需的联接+条件下生成的查询。

This will automatically add the required joins + conditions to the generated query.

在情况下,你真的希望拥有的所有关联你的结果返回太多,那么就使用保持包含()

In case you actually want to have all the associations returned in your results too, then just keep using contain() too

$this->Contacts
    ->find()
    ->contain('Users')
    ->matching('Users', function(\Cake\ORM\Query $q) {
        return $q->where(['Users.id' => 1]);
    });

您也可以将更深层次的关联的方式,通过在点谱写路径从知)语法查询::包含(,例如,如果你也有一个用户hasOne XYZ 关联,您可以通过 Xyz.id 使用过滤器

You can also target deeper associations that way, by using the dot notated path syntax known from Query::contain(), for example if you also had a Users hasOne Xyz association, you could filter by Xyz.id using

->matching('Users.Xyz', function(\Cake\ORM\Query $q) {
    return $q->where(['Xyz.id' => 1]);
})

从另一个表中选择,而不是

使用thse协会和你的简单要求,你也可以很容易地从对方查询,通过用户表,并只使用查询,即: :包括()来包括相关的接触,像

Select from the other table instead

With thse associations and your simple requirements, you could also easily query from the other side, ie via the Users table and use just Query::contain() to include the associated contacts, like

$this->Users
    ->find()
    ->contain('Contacts')
    ->where([
        'Users.id' => 1
    ])
    ->first();

所有的联系人,然后可以在实体中找到联系人属性。

这篇关于如何通过对相关车型的条件来过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆