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


How to retrieve only those records that do not have an associated record?

我正在使用CakePhp 3.x,并试图根据相关数据筛选数据。假设我有两个UsersProfiles模型

用户有一个配置文件,配置文件属于一个用户。

所以我想让那些没有配置文件的用户来帮助我如何应用这些条件?

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

我试过这样做,我认为这是错误的,然后我用contain尝试了它,但contain对相关数据进行了过滤,而不是对用户进行过滤,所以有什么方法可以获得那些没有配置文件的用户吗?

请参阅下面的链接:-

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

基于相关数据的数据过滤有三种类型。

1->匹配

2->无匹配

3->参见上方的链接

匹配此函数将过滤与指定关联相关的结果:目前是配置文件。

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

无匹配

matching()的反面是notMatching。此函数将更改查询,以便过滤与指定关联没有关系的结果:

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

你可以试试这样的东西:

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

希望这能有所帮助。