在CakePHP中有其他模型的多关系和ID [英] HasMany Relationship and ID from other Model in CakePHP

查看:140
本文介绍了在CakePHP中有其他模型的多关系和ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在使用登录用户ID的模型中创建hasMany关系。

I am wondering whether it is possible to create a hasMany Relationship in a Model which makes use of the ID of the logged in user.

示例:
一个提示有很多投票(来自不同的用户)。这很容易:

Example: One tip has many votings (from different users). This is easy:

public $hasMany = array(
   'TipVoting' => array(
        'className' => 'TipVoting',
        'foreignKey' => 'tip_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ));

现在我想获得所有提示,但想知道登录的用户hast是否已经投票。所以我想创建一个如下的Realtionship:

Now I want to get all Tips but want to know whether the logged in user hast voted this Tip already. So I would like to create a Realtionship which looks like this:

public $hasMany = array(
   'MyTipVoting' => array(
        'className' => 'TipVoting',
        'foreignKey' => 'tip_id',
        'dependent' => false,
        'conditions' => array('TipVoting.user_id' => $loggedinUser_id),
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

如何获取$ loggedinUser_id到这个模型?或者这是一个糟糕的方式来实现这个问题?

How do I get the $loggedinUser_id into this Model? Or is this a bad way of implementing this issue? Should I rather go for a seperate find on the TipVoting Model?

有没有想法?

谢谢! p>

Thanks!

推荐答案

使用可包含的行为。 http://book.cakephp.org/view/474/Containable

Use the containable behavior. http://book.cakephp.org/view/474/Containable

你不想定义一个不同的关系,你只是想能够通过相关的条件过滤。

You don't want to define a different relationship, you just want to be able to filter by associated criteria. Containable will allow you to do this.

只需使用TipVoting关系,在您的模型中执行以下操作:

With just the TipVoting relationship, in your model do this:

var $actsAs = array( 'Containable' );

在您的控制器动作中执行:

in your controller action do this:

$this->TipVoting->find( 'all', array( 
 'contain' => array( 
   'Vote' => array( 
    'conditions' => array( 
      'TipVoting.user_id' => $this->Auth->User('id') ), 
    'order' => 'TipVoting.id DESC' ) ) );

这篇关于在CakePHP中有其他模型的多关系和ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆