如何仅检索那些没有关联记录的记录?

时间:2016-04-09 13:17:32

标签: php cakephp associations cakephp-3.0 query-builder

我正在使用 CakePhp 3.x ,我正在尝试根据相关数据过滤数据。 假设我有两个模型用户个人资料

用户拥有一个个人资料和个人资料属于用户。

所以我想让那些没有资料的用户如此友善地帮助我如何应用这些条件?

$this->Users->find('all',[
  'conditions'=>['Profile.id'=>Null]
])

我正在尝试这样的事情我错了然后我尝试使用包含但是包含对关联数据进行过滤而不是用户那么有没有办法让那些没有个人资料的用户?

2 个答案:

答案 0 :(得分:1)

请参阅以下链接: -

http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-notmatching

在相关数据的基础上有三种类型的数据过滤。

1 - >的匹配

2 - >的 noMatching

3 - >见上面的链接

<强>匹配 此函数将过滤与指定关联相关的结果:现在是它的配置文件。

$this->Users->find()->matching('Profiles') //This will get those user how have profile 

<强> NoMatching

匹配()的反面是notMatching()。此函数将更改查询,以便筛选与指定关联无关的结果:

$this->Users->find()->noMatching('Profiles') //This will get those user how have no profile

答案 1 :(得分:0)

您可以尝试这样的事情:

$query = $this->Users->find()
  ->contain([
    'Profiles' => function ($q) {
      return $q
        ->select(['id', 'name'])  // Your profile fields, say id, name etc.
        ->where(['Profiles.id' => NULL]);
   }
]);

希望这有帮助。