我要做的是通过个人资料的评论来提取个人资料信息。我按预期得到了一切。没有返回错误,数组格式完美。我担心的是运行的查询。它为每个ID运行一个查询以获取其照片(查询的开头在下面的代码中的注释中注明)。我想这是用user_id获取照片的唯一方法吗?所有在单独的查询?还有更好的方法吗?
我正在描绘一张有40多条评论的个人资料,这可想而知。这是memcached的用武之地吗?
$profile = $this->Profile->find('first', array(
'conditions' => array('Profile.url' => $url),
'contain' => array(
'User' => array(
'fields' => array(
'User.id','User.name'
),
'Photo' => array(
'fields' => array(
'Photo.thumbnail','Photo.image'
)
)
),
'Comment' => array(
'User' => array(
'fields' => array(
'User.name'
),
'Photo' => array( // right here
'fields' => array(
'Photo.thumbnail'
)
)
)
)
)
));
编辑:
我显然有一个User表,还有一个Comment表。我还有一个Photo表,用于存储用户图像的URL,外键= user_id。因此,当我查询来自特定配置文件的所有评论并且它是Comment.user_id时,我还需要通过其user_id从Photo表中获取Photo.thumbnail。
答案 0 :(得分:1)
使用LEFT JOIN可以使速度更快。
编辑了 已编辑的代码以更好地回答问题(需要两个左连接 - 而不是一个)。SELECT c.text, i.profiles, p.photo_url
FROM comments AS c
LEFT JOIN profiles AS i on c.profile_id = i.id
LEFT JOIN photos AS p ON i.id = p.user_id
WHERE c.post_id = 32
LIMIT 20
这只是一个通用SQL,但会:
只有一个查询,您可以提取所有30条评论及其相关的个人资料。
希望它有所帮助!
答案 1 :(得分:1)
您可以将数组键'contains'替换为数组键'link',并为您构建左连接 - 请参阅linkable behavior。缺点是链接的所有关系必须是从hasOne或hasMany到belongsTo关系。
答案 2 :(得分:1)
您可能还想看看Nate在面包店中关于做“加入蛋糕方式”的文章。
http://bakery.cakephp.org/articles/view/quick-tip-doing-ad-hoc-joins-in-model-find