PostsTable :
$this->belongsToMany('Categories', [
'through' => 'CategoryPost'
]);
CategoriesTable :
$this->belongsToMany('Categories', [
'through' => 'CategoryPost'
]);
CategoryPostTable :
$this->belongsTo('Categories', [
'foreignKey' => 'category_id'
]);
$this->belongsTo('Posts', [
'foreignKey' => 'post_id'
]);
我想展示特定类别的帖子。例如" design"类别。
路线定义为:
$routes->connect('/blog/archive/:safe_name', ['controller' => 'Posts', 'action' => 'category'], ['pass' => ['safe_name']]);
category
控制器中的Posts
操作定义如下:
class PostsController extends AppController
{
...
public function category($safe_name = null)
{
$this->paginate = [
'contain' => ['Photos', 'Categories']
];
$posts = $this->Posts->find()->matching('Categories', function ($q) {
return $q->where(['Categories.safe_name' => $safe_name]);
});
$this->set('posts', $this->paginate($posts));
$this->set('_serialize', ['posts']);
}
...
}
但我得到的是:
Undefined variable: safe_name [APP/Controller\PostsController.php, line 188
任何人都可以帮我解决这个问题!我该怎么办? 抱歉英语不好。
和BTW我的cakephp版本是3.0。
答案 0 :(得分:3)
负责错误消息的代码是:
$posts = $this->Posts->find()->matching('Categories', function ($q) {
return $q->where(['Categories.safe_name' => $safe_name]);
});
因为在闭包内,变量$save_name
没有被定义。要解决该错误,请使用use
$posts = $this->Posts->find()->matching('Categories', function ($q) use ($safe_name) {
return $q->where(['Categories.safe_name' => $safe_name]);
});