-----
Phần x12. CakePHP2
– Sử dụng containable behavior
Xem (clip số 18a – chickenrainshop):
Dùng containable behavior để hạn chế thông tin khi truy vấn
cơ sở dữ liệu.
[BooksController.php action view]
public function view($slug = null) {
$options
= [
'conditions'
=> ['Book.slug' => $slug],
'contain'
=> ['Writer' => ['name', 'slug']]
];
$book
= $this->Book->find('first', $options);
if
(empty($book)) {
throw
new NotFoundException(__('Không tìm thấy quyển sách này'));
}
$this->set('book',
$book);
}
[View\Books\view.ctp]
<div class="books view">
<h2><?php echo __('Book'); ?></h2>
<dl>
<dt><?php
echo __('Title'); ?></dt>
<dd>
<?php
echo h($book['Book']['title']); ?>
</dd>
<dt><?php
echo __('Image'); ?></dt>
<dd>
<?php
echo $this->Html->image($book['Book']['image']); ?>
</dd>
<dt><?php
echo __('Info'); ?></dt>
<dd>
<?php
echo h($book['Book']['info']); ?>
</dd>
<dt><?php
echo __('Price'); ?></dt>
<dd>
<?php
echo h($book['Book']['price']); ?>
</dd>
<dt><?php
echo __('Sale Price'); ?></dt>
<dd>
<?php
echo h($book['Book']['sale_price']); ?>
</dd>
<dt><?php
echo __('Publisher'); ?></dt>
<dd>
<?php
echo h($book['Book']['publisher']); ?>
</dd>
<dt><?php
echo __('Publish Date'); ?></dt>
<dd>
<?php
echo h($book['Book']['publish_date']); ?>
</dd>
</dl>
</div>
<div class="related">
<h3><?php
echo __('Related Writers'); ?></h3>
<?php if
(!empty($book['Writer'])): ?>
<?php
foreach ($book['Writer'] as $writer): ?>
<?php
echo $this->Html->link($writer['name'], '/tac-gia/'.$writer['slug']);
?>
<?php
endforeach; ?>
<?php endif;
?>
</div>
<div class="related">
<h3><?php
echo __('Related Comments'); ?></h3>
<?php if
(!empty($book['Comment'])): ?>
<?php foreach
($book['Comment'] as $comment): ?>
<?php
endforeach; ?>
</table>
<?php endif; ?>
</div>
Xem (clip số 18b – chickenrainshop):
Hiển thị thông tin bình luận của mỗi quyển sách.
Khai báo sẽ sử dụng containable behavior trong
[Model\Comment.php]
class Comment extends AppModel {
public $actsAs =
['Containable'];
[View\Books\view.ctp]
Thêm đoạn mã sau vào cuối tập tin:
<div class="related">
<h3><?php
echo __('Related Comments'); ?></h3>
<?php if
(!empty($comments)): ?>
<?php foreach
($comments as $comment): ?>
<?php
echo $comment['User']['username'].' đã gửi:
'.'"'.$comment['Comment']['content'].'"'; ?> <br>
<?php
endforeach; ?>
</table>
<?php endif; ?>
</div>
-----------
Cập nhật 9/5/2017
-----------