我对 Cakephp 很陌生。我的所有模型协会都工作正常,但这个问题困扰着我,我还没有找到任何人解决了类似的问题。就这样..
我有 4 张 table :
人
+-----+-------------------+ | Id | first_name | +-----+-------------------+ | 1 | jim | | 2 | bob | +-------------------------+
facility_project_people
+-----+---------------------+-----------+ | Id | facility_project_id | person_id | +-----+---------------------+-----------+ | 1 | 5 | 1 | | 2 | 6 | 1 | | 3 | 7 | 2 | +---------------------------+-----------+
facility_projects
+-----+-------------+-----------+-----------+ | Id | facility_id | project_id| type_id | +-----+-------------+-----------+-----------+ | 1 | 1 | 1 | 1 | | 2 | 2 | 3 | 2 | | 3 | 2 | 5 | 3 | +-------------------+-----------+-----------+
projects
+-----+-------------+ | Id | name | +-----+-------------+ | 1 | Audit | | 2 | Inventory | | 3 | Tax | | 4 | Consulting | +-------------------+
So I have people who can be involved in many projects per facility
I'm trying to make a model association to get from Person to the Projects they are involved with.
The MySQL query would be something like:
SELECT
p.first_name,
pr.name
FROM <code>people</code> p
left join <code>facility_project_people</code> fpp
ON p.<code>id</code> = fpp.<code>person_id</code>
left join <code>facility_projects</code> fp
ON fpp.facility_project_id = fp.id
left join <code>projects</code> pr
ON fp.project_id = pr.id
Using a hasAndBelongsToMany Assocation, I understand how to get as far as the facility_projects table.
class Person extends AppModel {
public $hasAndBelongsToMany = array(
PersonFacilityProject' => array(
'className' => 'Project',
'joinTable' => 'facility_project_people',
'foreignKey' => 'person_id',
'associationForeignKey' => 'facility_project_id',
),
}
}
显然这并不能满足我的需要
查看某人时,我想查看相关项目,但我不知道如何访问项目表。我希望能够向关联添加另一个连接表和外键,但 cakephp 似乎不允许这样做。
我很欣赏任何见解。
最佳答案
您没有说明您使用的 cakephp 版本。但是,您可以使用“contain”来执行此操作(因为您的模型并非全部直接相关),如下所示:
$conditions = [
'contain' => [
'FacilityProjectPerson'=>[
'FacilityProject'=>[
'Project'=>[
'fields'=>['Project.name']
],
],
],
],
// 'conditions' => [//just in case you need conditions for selecting people
// 'Person.id' => $this->id,
// ],
'fields'=>['Person.first_name']
];
$this->Person->find('all',$conditions);
关于php - Cakephp HABTM 需要多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26045699/