gpt4 book ai didi

php - CakePhp单页获取多表数据

转载 作者:行者123 更新时间:2023-11-29 12:12:51 24 4
gpt4 key购买 nike

我是 cakePHP 的新手,尝试创建一个博客网站,用户在类别选择后添加博客,我有一个类别表:字段:category_id、名称和帖子表:字段:id、category_id、标题、正文。我想将所有类别提取到下拉列表中。当用户添加新帖子时,他们必须首先选择类别,然后他才能发布任何内容..

我的帖子 Controller :

<?php 


class PostsController extends AppController{



public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session','Paginator');

public function index(){

$this->Paginator->setting = array(
'limit' =>'10',
'order' => array('Post.id' =>'Desc')
/*'conditions' => array(
'Post.user_id' => AuthComponent::user(id)
)*/
);

$arrPosts = $this->Paginator->paginate('Post');

$this->set('posts', $arrPosts);

}

public function view($id = null){

if(!$id){

throw new NotFoundException(__("Error Processing Request ID"));

}
$post =$this->Post->findById($id);
if(!$post){

throw new NotFoundException(__("Error Processing Request POST"));

}
$this->set('post',$post);
}

public function add(){

// HERE I want to fetch all categoryies from categories table and want to send to view

if($this->request->is('post')){

$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}


}
}
?>

我想以添加形式显示我的类别:

请帮助我...

最佳答案

在 Controller 操作中,您需要使用 $this->set() 来设置 View 变量。只要您在 Post 模型中正确设置了关联,您就应该能够使用:-

$this->set('categories', $this->Post->Category->find('list'));

Cake 的 FormHelper 应该自动知道 Post.category_id 表单字段希望成为以 $categories 作为选项的选择输入。

还有一点,最好在处理表单后设置 View 变量,因为如果正确保存,则不需要它们,因此可以减少 1 次数据库查询次数。

如果您使用 find('all') 检索类别,您需要将其转换为 find('list') 使用的格式,这样可以轻松地使用 Hash::combine():-

完成
$categories = $this->Post->Category->find('all');
$this->set(
'categories',
Hash::combine($categories, '{n}.Category.id', '{n}.Category.name')
);

这样做的唯一真正值(value)是如果您需要 $categories 来做其他事情。

关于php - CakePhp单页获取多表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30346553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com