如何在 cakephp 中使用 where 子句分页加入多对多 table?
How to paginate joined many-to-many table with where clause in cakephp?
我有两个表,它们由另一个表连接在一起。表格是:
PostsTable:
$this->belongsToMany('Categories', [
'through' => 'CategoryPost'
]);
类别表:
$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']]);
Posts
控制器中的category
动作定义如下:
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
谁能帮我解决这个问题!我该怎么做?
抱歉英语不好。
顺便说一句,我的 cakephp 版本是 3.0。
php 中的闭包不继承更高作用域中的变量
导致错误消息的代码是这样的:
$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]);
});
我有两个表,它们由另一个表连接在一起。表格是:
PostsTable:
$this->belongsToMany('Categories', [
'through' => 'CategoryPost'
]);
类别表:
$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']]);
Posts
控制器中的category
动作定义如下:
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
谁能帮我解决这个问题!我该怎么做? 抱歉英语不好。
顺便说一句,我的 cakephp 版本是 3.0。
php 中的闭包不继承更高作用域中的变量
导致错误消息的代码是这样的:
$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]);
});