我正在尝试显示关系中第三个表中的字段,在检查了此处的帖子和文档后,我仍然陷入困境。我有 3 个模型都以某种方式相关。我在这里找到了类似的帖子,但我仍然无法让它发挥作用。如果我在文档中的某个地方错过了这一点,我会很抱歉,但我已经阅读了相当多的内容并尝试了很多。我现在对此猜测太多,所以我需要帮助。
1)Tutorsession - belongsto teachers,
2) Teacher -has 1 user,hasmany tutorsessions
3) User- has 1 teacher, //////I want to display a field from this table given I display tutorsessions
In controller
$this->set('tutor',
$this->Tutorsession->find('first',
array(
'conditions' => array('Teacher.user_id' => $id),
'contain' => 'User.username'
)
)
); //////////no error but no results
from view echo '<td>'. $item['User']['username'].'</td>'; ///////error user undefined
导师 session 会自动从教师表中获取行,但不会在 findall 上设置模型时从用户表中获取行。
我想显示用户表中的用户名。我显示了 coachsession 表,然后可以显示具有模型关联的教师表,但我无法从教师表转到用户表以从用户 id 获取用户名作为公共(public)字段。我已经检查了下面的文档,我不确定为什么我的代码无法显示用户表中的用户名。
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
update: here are the models
class User extends AppModel {
public $hasOne = array(
'Teacher' => array(
'className' => 'Teacher',
'dependent' => true
)
class Tutorsession extends AppModel
{
public $name='Tutorsession';
public $belongsTo = array(
'Teacher' => array(
'className' => 'Teacher',
'foreignKey' => 'teacher_id'
)
class Teacher extends AppModel
{
public $name='Teacher';
public $hasMany = array('Tutorsession');
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
最佳答案
在模型中添加可容纳的行为
public $actsAs = array('Containable');
在 Controller 中执行以下查询
$contain = array('Teacher' => array('User'));
$this->set('tutor', $this->Tutorsession->find('first',array(
'conditions' => array('Teacher.user_id' => $id),
'contain' => $contain
)));
关于php - 显示第三个表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050182/