如何只检索那些没有关联记录的记录?
How to retrieve only those records that do not have an associated record?
我正在使用 CakePhp 3.x 并且我正在尝试根据关联数据过滤数据。
假设我有两个模型 Users 和 Profiles
用户有一个个人资料,个人资料属于一个用户。
所以我想让那些没有个人资料的用户帮助我如何申请条件?
$this->Users->find('all',[
'conditions'=>['Profile.id'=>Null]
])
我是这样尝试的,但我觉得这是错误的,然后我用 contain 尝试了它,但 contain 对关联数据进行了过滤,而不是对用户进行过滤,所以有什么方法可以让那些没有个人资料的用户?
您可以尝试这样的操作:
$query = $this->Users->find()
->contain([
'Profiles' => function ($q) {
return $q
->select(['id', 'name']) // Your profile fields, say id, name etc.
->where(['Profiles.id' => NULL]);
}
]);
希望对您有所帮助。
见下面的 Link :-
http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-notmatching
基于关联数据的数据过滤分为三种。
1 -> 匹配
2 -> 不匹配
3 -> 请参阅上面的 Link
匹配
此功能将过滤与指定关联相关的结果:目前是配置文件。
$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
我正在使用 CakePhp 3.x 并且我正在尝试根据关联数据过滤数据。 假设我有两个模型 Users 和 Profiles
用户有一个个人资料,个人资料属于一个用户。
所以我想让那些没有个人资料的用户帮助我如何申请条件?
$this->Users->find('all',[
'conditions'=>['Profile.id'=>Null]
])
我是这样尝试的,但我觉得这是错误的,然后我用 contain 尝试了它,但 contain 对关联数据进行了过滤,而不是对用户进行过滤,所以有什么方法可以让那些没有个人资料的用户?
您可以尝试这样的操作:
$query = $this->Users->find()
->contain([
'Profiles' => function ($q) {
return $q
->select(['id', 'name']) // Your profile fields, say id, name etc.
->where(['Profiles.id' => NULL]);
}
]);
希望对您有所帮助。
见下面的 Link :-
http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-notmatching
基于关联数据的数据过滤分为三种。
1 -> 匹配
2 -> 不匹配
3 -> 请参阅上面的 Link
匹配 此功能将过滤与指定关联相关的结果:目前是配置文件。
$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