模型与自身相关,双向

时间:2013-12-30 01:25:38

标签: cakephp has-many

我有一张人员表,人们通过身份证与其他人联系。我相信这应该是一个单独的表,这是这种关系的标准,但我希望能够在查看单个记录时检索关联的人,无论该记录存储在哪个键中。例如:

table: people
id | first_name | last_name

table: people_associations
id | person_one_id | person_two_id

model: person
$hasMany = array(
    "Associates" => array(
        "className" => "Person",
        "foreignKey" => ????
    )
);

如何使Associates引用foreignKey是person_one_id还是person_two_id的关系,并将所有结果返回到一个整齐的数组中?

1 个答案:

答案 0 :(得分:0)

我相信我设法实施了一个解决方案。关键部分是使用正确的finderQuery,它检查user_association表中的用户相关字段,并重新排列“first_id”和“second_id”字段,以确保Cake能够仅使用一个外键字段链接所有关联(在这个例子中是“first_id”。

请注意我使用了下表:

table: users
id | name

table: user_associations
id | first_id | second_id

<强> 1。定义UserAssociation模型

class UserAssociation extends AppModel {

    public $belongsTo = array(
        'Second' => array(
            'className' => 'User',
            'foreignKey' => 'second_id',
        )
    );
}

<强> 2。定义用户模型

class User extends AppModel {

    //fields definition skipped for brevity

    public $hasMany = array(
        'UserAssociations' => array(
            'className' => 'UserAssociation',
            'foreignKey' => 'first_id',
            'finderQuery' => 'SELECT * FROM (SELECT UserAssociations.id, UserAssociations.first_id, UserAssociations.second_id 
                FROM user_associations as UserAssociations 
                WHERE (UserAssociations.first_id = {$__cakeID__$})
                UNION 
                SELECT UserAssociations2.id, UserAssociations2.second_id as first_id, UserAssociations2.first_id as second_id 
                FROM user_associations as UserAssociations2 
                WHERE (UserAssociations2.second_id = {$__cakeID__$}) ) as UserAssociations '
        )
    );
}

第3。结果

现在,当我按如下方式运行示例查询时:

$this->User->recursive = 2;
$this->set('user_data', $this->User->read());

我将UserAssociations作为结果的一部分,并提供相关人员记录 - 这是在视图中捕获的var_dump($ user_data)输出:

array (size=3)
  'User' => 
    array (size=2)
      'id' => string '1' (length=1)
      'name' => string 'John Doe' (length=8)
  'UserAssociations' => 
    array (size=2)
      0 => 
        array (size=4)
          'id' => string '1' (length=1)
          'first_id' => string '1' (length=1)
          'second_id' => string '18' (length=2)
          'Second' => 
            array (size=2)
              ...
      1 => 
        array (size=4)
          'id' => string '2' (length=1)
          'first_id' => string '1' (length=1)
          'second_id' => string '17' (length=2)
          'Second' => 
            array (size=2)
              ...

希望这有帮助!