dream04110 2010-04-06 02:06
浏览 50
已采纳

如何为我的CakePHP模型关联使用不同的id字段?

I have an one to many association in which a Thing can have many Statuses defined as below:

Status Model:

class Status extends AppModel
{
    var $name = 'Status';

    var $belongsTo = array(
        'Thing' => array(
            'className' => 'Thing',
            'foreignKey' => 'thing_id',
    );
}

Thing Model:

class Thing extends AppModel
{
    var $name = 'Thing';    

    var $belongsTo = array(
        // other associations
    );

    var $hasMany = array(
        'Status' => array(
            'className' => 'Status',
            'foreignKey' => 'thing_id',
            'dependent' => false,
            'order' => 'datetime DESC',
            'limit' => '10',
        ),
        // other associations
    );
}

This works OK, but I would like Thing to use a different id to connect to Status. E.g. Thing would use 'id' for all of it's other associations but use 'thing_status_id' for it's Status association.

How can I best do this?

  • 写回答

4条回答 默认 最新

  • douweilaton2762 2010-04-06 07:23
    关注

    In the end I could only get it to work by using a finderQuery with a SQL subquery.

    Here is my Model:

    class Thing extends AppModel
    {
        // ...
    
        var $hasMany = array(
            'Status' => array(
                'className' => 'Status',
                'foreignKey' => 'thing_id',
                'dependent' => false,
                'limit' => 10,
                'finderQuery' => '
                    SELECT Status.* 
                    FROM statuses AS Status 
                    WHERE Status.thing_id = (
                        SELECT Thing.status_thing_id 
                        FROM things AS Thing 
                        WHERE Thing.id = {$__cakeID__$}
                    )
                    ORDER BY Status.datetime DESC
                    LIMIT 0, 10',
            ),
        ),
    
        // ...
    }
    

    The really weird thing is if I remove the 'limit' => 10 line the query no longer works properly, even though that line doesn't do anything (I still need the LIMIT 0,10 in my SQL).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀