問題描述
我有一個 CakePHP 1.3 應用程序并且非常喜歡用于獲取數據的可包含行為.
I have a CakePHP 1.3 app and really enjoy the Containable behavior for fetching data.
假設我的帖子與評論是一對多的關系.我使用 Containable 來查詢(用于分頁)所有帖子和所屬評論的列表.但我只對每個帖子有多少評論感興趣.我沒有找到任何方法來實現這個查詢,而無需獲取所有評論行.我試過了:
Let's assume I have Posts in one-to-many relationship with Comments. I use Containable to query (for pagination) a list of all Posts and the belonging Comments. But I'm only interested in how many Comments each Post has. I did not found any way to achieve this query with containable without fetching all rows of Comments. I tried:
$this->paginate=array(
'fields' => 'Post.title, Post.created',
'contain' => array('Comment'=>'COUNT(*) AS count'),
);
導致模型評論"與模型計數"錯誤消息無關.
results in 'Model "Comment" is not associated with model "Count"' error message.
$this->paginate=array(
'fields' => array('Post.title, Post.created'),
'contain' => array('Comment'=>array('fields'=>'COUNT(*) AS count'),
);
不起作用,結果集為每個 Post 包含一個空的 Comment 數組,除了最后一個,其中包含計數字段,但包含所有評論的數量,而不僅僅是屬于的評論.
does not work, result set contains for each Post an empty Comment array except for the last one, where it contains the count field, but having the number of all comments not just the belonging ones.
我的另一個猜測是
$this->paginate=array(
'fields' => 'Post.title, Post.created, COUNT(Comment.id)',
'contain' => array('Comment'=>array('fields'=>''),
);
但這會導致錯誤,因為hasMany關系是獨立查詢的,所以Answer表不在查詢Post條目中.如何計算帖子的評論數量?
but this results in an error, because hasMany relationships are queried independently, so the Answer table is not in the query for the Post entries. How can I count the number of Comments a Post has?
推薦答案
嗯,最好的方法是在 posts
中設置一個名為 comment_count
的字段表并將此鍵添加到評論模型 $belongsTo Post 數組:
Well, the best way to do this is to set up a field called comment_count
in the posts
table and add this key to the Comment model $belongsTo Post array:
'counterCache' =>真實
每次評論發生任何事情時,相關帖子中的comment_count字段都會更新(實際上,它每次都會重新計數,而不是僅僅添加或刪除).
Every time anything will be happening with the comments, the comment_count field in the related post will be updated (actually, it recounts every time, instead of just adding or deleting).
更好,因為當您為用戶獲取數據時,它的方式會更快,甚至不會觸及評論表.由于您使用的是 Containable 行為,我猜您正在尋找速度和輕量級.
It's better, because when you fetch data for the user, its way faster and doesn't even touch the comments table. Since you're using the Containable behaviour I guess speed and lightweight is what you're looking for.
這篇關于CakePHP 模型:可包含中的 COUNT(*)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!