【问题标题】:CakePHP Plugin Model Associations Not WorkingCakePHP 插件模型关联不起作用
【发布时间】:2012-09-13 01:20:14
【问题描述】:

场景:我有一个 CakePHP 应用程序,带有一个名为 Fruit 的插件。 Fruit Plugin 包含一个到 TagsController.php 的路由,其中​​ index 的 Action 指向 index.ctp

标签模型有一个关联。 user_id

问题:即使我在 Model->find('all'... ..

标签控制器

public function index($ajax = false) {
    $this->Tag->recursive = 2;
    $tags = $this->Tag->find('all', array('conditions' => array('User.id' => $this->Auth->user('id')), 'joins'=>array(
    array(
         'table'=>'users',
         'alias'=>'User',             
         'conditions'=>array(
              'User.id=Tag.user_id'
         )
    ),
    )));

    print_r($tags);

    $this->set('tags', $this->paginate());

    if($ajax == 'ajax')
    {
        $this->layout = 'ajax';
    }
}

标签模型

App::uses('FruitAppModel', 'Fruit.Model');
class Tag extends FruitAppModel {

public $name = 'Tag';
public $uses = array('User');
public $belongsTo = array(
    'User' => array(

        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

用户模型

App::uses('AppModel', 'Model');

class User extends AppModel {

public $name = 'User';
public $displayField = 'username';

public $hasMany = array(        
    'Tag' => array(
        'className' => 'Fruit.Tag',
        'foreignKey' => 'tag_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),

);

我已经在这个问题上停留了几个小时,因此非常感谢任何关于我可以尝试的新想法。我已经很好地梳理了stackoverflow,我只是在兜圈子,我需要一双新的眼睛。任何想法都会很棒。

谢谢!

  • 杰夫

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.1 cakephp-2.2


    【解决方案1】:

    我认为你已经尝试了很多并且让它变得更复杂,试试这个代码它会给你想要的输出。

    在用户模型中:

    public $hasMany = array(        
    'Tag' => array(
        'className' => 'Fruit.Tag',
        'foreignKey' => 'user_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
    

    在控制器中:--

    $this->Tag->recursive = 1;
    
     $this->paginate = array(
        'conditions' => array('Tag.user_id' => $this->Auth->user('id'))
    );
    $data = $this->paginate('Tag');
    pr($data);
    $this->set(compact('data'));
    

    【讨论】:

    • 反之呢?如果我想将插件中的模型关联到属于“核心”模型?
    猜你喜欢
    • 2012-07-06
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多