I'm twiting

访问统计

free counters

Saving a record along with its related records having hasMany association

For saving a record along with its related records having hasMany association, the data array should be like this:
Array
(
[Article] => Array
(
[title] => My first article
)
[Comment] => Array
(
[0] => Array
(
[comment] => Comment 1
[user_id] => 1
)
[1] => Array
(
[comment] => Comment 2
[user_id] => 2
)
)
)
The command for saving the above $data array would look like this:

cakephp的counterCache功能

场景:有两张表cabinet(机柜)表和server表。其中cabinet有一个字段叫server_count,用于记录有多少服务器在每个机柜上。
逻辑:每次添加或减少server,我们都需要手动更新server_count的值。通过counterCache,我们可以让cake代劳。只需要在定义我们的server model的时候加上
var $belongsTo = array(
‘Cabinet’ => array(’counterCache’ => true)
);
如此,当我们新增或减少server,cake将自动的修改server_count的值。

用cakephp创建复杂查询

例如这样:
$conditions['or'][] = array( “Group.group_name LIKE” => “%{$keyWord}%”);
$conditions['or'][] = array( “Group.comment LIKE” => “%{$keyWord}%”);
这两个条件就是or的关系。当然可以再加一个and的数组。通过这种方式去创建复杂查询。

cakephp分页功能(paginator)

在controller里定义属性:
var $paginate = array(
‘Group’ => array(
‘limit’ => 10
));
在action抓数据的时候用:
$groups = $this->paginate( ‘Group’, $conditions );
$this->set( ‘groups’, $groups );
在需要用到分页的地方加上:
<?php echo $this->renderElement(’pagination’); ?>
然后cake会去找pagination.ctp这个element的。贴一下我的分页:
<form action=”<?php echo preg_replace(’/page:(\d+)/’, ”, $paginator->url()); ?>”>
<table width=”95%” border=”0″ align=”center” cellpadding=”8″ cellspacing=”0″>
<tr>
<td width=”65%” colspan=”7″ align=”center” bgcolor=”#FFFFFF” style=”font-size:14px;”>
当前页<span class=”font_orange”><?php echo  $paginator->current(); ?></span>
总页数<span class=”font_blue”><?php echo $paginator->counter(array( ‘format’ => ‘%pages%’ )); ?></span>
<?php echo $paginator->first(’首页’); ?>
<?php echo $paginator->prev( ‘上一页’ ); ?>
<?php [...]