我有这种结构和表格的树模型:
Rate:
id, model_name, object_id
1 , SocialPost, 12
public $belongsTo => array(
'SocialPost' => array(
'className' => 'Social.SocialPost',
'foreignKey' => 'object_id',
'conditions' => array(
'Rate.object_id = SocialPost.id',
),
)
)
SocialPost: id,file_id
public $hasOne = array(
'File' => array(
'className' => 'File',
'foreignKey' => false,
'conditions' => array(
'File.id = SocialPost.file_id',
),
),
);
文件: id,title
所有树模型都可以包含
此代码在SocialPostsController中运行良好:
$posts = $this->SocialPost->find('all', array(
'limit' => 5,
'contain' => array(
'File'
)
));
输出:http://pastie.org/private/9ixxufncwlr3tofgp8ozw
但是RatesController中的这段代码为所有SocialPost返回相同的文件:
$mostRated = $this->Rate->find('all', array(
'limit' => $count,
'contain' => array(
'SocialPost' => array(
'File'
)
)
));
输出:http://pastie.org/private/lbqryo1gxgvxjb5omfwrw
这里有什么问题?
答案 0 :(得分:1)
我认为你们的关联应该属于所有人:
class Rate extends AppModel {
public $belongsTo = array(
'SocialPost' => array(
'className' => 'Social.SocialPost',
'foreignKey' => 'object_id',
)
);
}
class SocialPost extends AppModel {
public $belongsTo = array(
'File'
);
}
然后你的find命令看起来像:
$mostRated = $this->Rate->find('all', array(
'limit' => $count,
'contain' => array(
'SocialPost.File'
)
));
另外,我会仔细检查您的'className' => 'Social.SocialPost'
是否正确。这意味着SocialPost
模型存在于名为Social
的插件中。