CakePHP 插件模型关联不起作用

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

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

标签模型有一个关联。用户 ID

问题:即使我向 Model->find('all'... 添加连接选项,['User'] 索引未定义。我不知道该怎么做,这是我的代码.. ..

标签 Controller

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 进行了很好的梳理,但我只是在原地踏步,我需要用新的眼光来看待这个问题。任何想法都会很棒。

谢谢!

  • 杰夫

最佳答案

我认为您已经尝试了很多并使其变得更加复杂,尝试此代码它会给您所需的输出。

在用户模型中:

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

在 Controller 中:--

$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'));

关于CakePHP 插件模型关联不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12398186/

相关文章:

php - OAuth 重定向后 session 丢失

CakePHP:如何在 app_controller 中使用模型

php - 如何使用 CakePhp 克隆/复制一条 sql 记录?

php - 这是使用 CakePHP 2.4 添加 META 标签的正确方法吗?

CakePHP 2 独立的登录表

Bootstrap 中的 Cakephp ClassRegistry::init

SSL蛋糕PHP表单

mysql - 在一个应用程序中使用两个或三个表

javascript - 单击其他按钮时如何使div自动隐藏

php - CakePHP 2.1.3 单个页面的 SEO 元描述与 default.ctp