gpt4 book ai didi

php - 这个协会怎么成立?

转载 作者:行者123 更新时间:2023-12-04 18:18:49 25 4
gpt4 key购买 nike

我正在使用 cakephp 框架来开发应用程序,并且在完全理解这些模型之间的关联时遇到了一些麻烦。您可以在下面看到四个模型及其相关的数据库字段。

User
id

Profile
id
user_id

Post (A blog post on the users profile)
id
profile_id
topic_id

Topic (A topic for a blog post)
id
name

以下是目前的协会:
User
hasOne: Profile

Profile
hasMany: Posts

Post
belongsTo: Topic, Profile

现在我的问题。我不确定您是否必须定义像 User hasMany Posts 这样的关联。或者如果它已经被假定是因为 User hasOne ProfileProfile hasMany Posts .我的另一个问题是定义帖子与其主题之间的关系。
  • 个人资料可以有无限的帖子
  • 帖子必须与个人资料相关联
  • 一个帖子只能有一个主题
  • 主题表包含所有主题的列表
  • 帖子不需要主题

  • 鉴于这些标准,我的关联应该如何看待?我对关联所做的所有研究都只展示了简单的例子。

    我正在使用 CakePHP 2.1.3 版

    感谢您提前提供任何和所有帮助和/或建议

    最佳答案

    您可以递归地找到关联的关联,甚至更好的是,使用 Containable。

    在模型中(我建议把它放在 AppModel 中,因为我发现自己对所有东西都使用了 Containable):

    class AppModel extends Model {
    public $actsAs = array('Containable');
    ...
    }

    然后,当您为用户调用读取(或查找或分页)时,很可能在您的 Controller 中,执行以下操作:
    $this->User->contain(array(
    'Profile' => array(
    'Post'
    )
    ));
    $data = $this->User->read();
    $set('user',$data);

    如果您将该数据设置到您的 View 中,您就可以从 $user['Profile']['Post'][0]['id'] 访问其中一篇文章的 ID。 .

    现在对于您的下一个问题,您可以有条件关联。
    public $hasMany = array(
    'Topic' => array(
    'className' => 'Topic',
    'conditions' => 'Post.topic_id IS NOT NULL'
    )
    )

    关于php - 这个协会怎么成立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11146266/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com