【问题标题】:CakePHP self-join a HABTM table without breaking Cake's automationCakePHP 在不破坏 Cake 自动化的情况下自行加入 HABTM 表
【发布时间】:2012-07-08 18:17:24
【问题描述】:

我有一张运动员桌。运动员有教练,教练也是运动员。运动员可能有多个教练。

为了处理这个问题,我创建了一个运动员表,该表使用一个带有 id 字段、运动员 ID 字段和教练 ID 字段的连接表。运动员 ID 和教练 ID 字段都指向运动员表的 id 字段。

通常,根据 Cake 约定,我必须将我的两个字段都命名为运动员 ID,但我发现以下链接显示了如何处理它:http://book.cakephp.org/1.2/view/851/Multiple-relations-to-the-same-model

根据 Cake 的约定,我将加入表命名为运动员运动员,但我不确定它是否能正常工作?将其称为运动员教练似乎是有道理的,但我敢打赌这可能会破坏 Cake 的自动功能。

这是否适用于名为 sports_athletes 的连接表?这是正确的方法吗?有没有更好的办法?

【问题讨论】:

    标签: php cakephp has-and-belongs-to-many cakephp-model


    【解决方案1】:

    这是我第一次在这里回答问题,所以如果我的回答不标准,我提前道歉。不久前,我写了一个社交网络应用程序,它带有一个用户模型,它有一个 HABTM 自我加入。假设“friends_users”的连接表,我的用户模型关联看起来像这样:

    public $hasAndBelongsToMany = array(
    'Friend' => array(
        'className' => 'User',
        'joinTable' => 'friends_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'friend_id', 
        'unique' => true
    )
    );
    

    假设我想为特定用户创建所有朋友姓名的列表,我可以这样做。

    <ul>
    <?php foreach($user['User']['Friend'] as $friend): ?>
    <li><?php echo $friend['name']; ?></li>
    <?php endforeach; ?>
    </ul>
    

    因此,只要您在 HABTM 关联中指定表的新名称、foreignKey 和 associatedForeignKey,那么您将连接表命名为什么并不重要(我仍然尝试遵循良好的蛋糕命名约定)正确覆盖 Cake 默认值。所以在你的情况下,你可以在你的运动员模型中做这样的事情(假设有一个运动员教练的连接表):

    public $hasAndBelongsToMany = array(
    'Coach' => array(
        'className' => 'Athlete',
        'joinTable' => 'athletes_coaches',
        'foreignKey' => 'athlete_id',
        'associationForeignKey' => 'coach_id', 
        'unique' => true
    )
    );
    

    要显示特定运动员的教练列表(可能在运动员的视图方法中),您可以执行以下操作:

    <ul>
    <?php foreach($athlete['Athlete']['Coach'] as $coach): ?>
    <li><?php echo $coach['name']; ?></li>
    <?php endforeach; ?>
    </ul> 
    

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 2011-08-19
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多