【问题标题】:HABTM only working one wayHABTM 仅以一种方式工作
【发布时间】:2011-07-12 18:44:50
【问题描述】:

我有用户和事件,以及 events_users 的共享表,以及设置到此连接表的用户/事件之间的 HABTM。

用户架构
id, …, …

事件架构
id,
user_id {this is the Owner of the event}

events_users 架构
id
user_id
event_id


用户模型

public $hasAndBelongsToMany = array(
    'Event' => array(
        'className' => 'Event',
        'joinTable' => 'events_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'event_id',
        'unique' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    )
);

事件模型

var $hasAndBelongsToMany = array(
    …
    …

    'SharedUser' => array(
        'className' => 'User',
        'joinTable' => 'events_users',
        'foreignKey' => 'event_id',
        'associationForeignKey' => 'user_id',
        'unique' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    )
);

它使用脚手架的添加/编辑表单很好地创建了 events_users 数据库条目,但是当我尝试拉它时,我得到了所有事件,而不仅仅是他们通过连接表“访问”的事件。当我查看事件时,它会自动向我显示使用此联接表的关联用户。

尝试从 users_controller 拉取用户有权“访问”的事件:

// this throws error of Unknown column 'EventUser.user_id' in 'where clause' (no matter what combination of pluralization or capitalization and underscore, ie EventUser, events_users, Events_Users)
$events = $this->User->Event->find('all', array('conditions'=> array('EventUser.user_id'=> $id))); 

// this throws error of Undefined property: UsersController::$EventUser 
$events = $this->User->Event->find('all', array('conditions'=> array('UsersEvents.user_id'=> $id))); 

// I would think this just gives the ones they "own", i have a user_id column in Event for the creator of event, but it returns empty
$events = $this->User->Event->find('all', array('conditions'=> array('user_id'=> $id)));  


// This gives me all events
$events = $this->User->Event->find('all');

【问题讨论】:

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


    【解决方案1】:
    $user = $this->User->find('first', array('conditions' => array('User.id' => $id));
    debug($user['Event']);
    

    可能contain 只有Event 模型,如果有更多的东西附加到用户模型你不想要。

    【讨论】:

    • arg,想拔头发。谢谢德塞兹。当我这样做时,我得到了错误,但后来我阅读了文档,发现这意味着它没有找到任何东西。然后我终于注意到了 ID 的值...原来使用 CakeDC 用户插件,我将 Slug 而不是 ID 传递给 Users_controller 的视图函数。我将 find 改为匹配 slug,然后抓取返回用户的事件表单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2020-07-30
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多