繁体   English   中英

如何关联两个 cakephp 型号?

[英]How to relate two cakephp models?

我是 CakePHP 2.x 的初学者,我刚刚完成了 CakePHP Cookbook 中的简单身份验证和授权应用程序示例。

我的代码几乎是该教程和前两个教程( 博客教程博客教程 - 添加图层)的完全相同的副本

在我的帖子列表视图(PostsController 的索引)上,该表显示了一个带有 user_id 的新列,因为我已将该列添加到原始 Posts 表 (mySQL) 中。

我想显示用户的用户名而不是帖子所有者的 user_id。 我被告知我可以使用 Containable 以及一些 model 属性,但我的知识现在还不是很先进。

换句话说,我希望帖子中的每个帖子都包含 ID 等于 user_id 的用户 object。

后 model

<?php 
    class Post extends AppModel{
    //public $hasOne = 'User';
    //public $actsAs = array('Containable');
    public $validate = array(
    'title' => array(
        'rule' => 'notBlank'            #NOT NULL
    ),
    'body' => array(
        'rule' => 'notBlank'            #NOT NULL
    )
);
   
    public function isOwnedBy($post, $user) {
        return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false;
    }
}

用户 model

 <?php

    // app/Model/User.php
    App::uses('AppModel', 'Model');
    App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');

    class User extends AppModel {
    //public $hasMany = 'Post';
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => 'notBlank',
                'message' => 'A username is required'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => 'notBlank',
                'message' => 'A password is required'
            )
        ),
        'role' => array(
            'valid' => array(
                'rule' => array('inList', array('admin', 'author')),
                'message' => 'Please enter a valid role',
                'allowEmpty' => false
            )
        )
    );
    
    // Password Hashing

    public function beforeSave($options = array()) {
        if (isset($this->data[$this->alias]['password'])) {
            $passwordHasher = new BlowfishPasswordHasher();
            $this->data[$this->alias]['password'] = $passwordHasher->hash(
                $this->data[$this->alias]['password']
            );
        }
        return true;
    }

// ...
}

帖子 Controller

<?php

class PostsController extends AppController{
    public $helpers = array('Html', 'Form');
    
    public function index(){
        $this->set('posts', $this->Post->find('all'));
        $this->layout= "test";
    }
    
    public function view($id = null) {
    $this->layout= "test";
    if (!$id) {
        throw new NotFoundException(__('Post inválido (NULL ID)'));
    }

    $post = $this->Post->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Post inválido (NO POSTS WITH THAT ID)'));                
    }
    $this->set('post', $post);
    }
    
    
    
    public function isAuthorized($user) {
    // All registered users can add posts
    if ($this->action === 'add') {
        return true;
    }

    // The owner of a post can edit and delete it
    if (in_array($this->action, array('edit', 'delete'))) {
        $postId = (int) $this->request->params['pass'][0];
        if ($this->Post->isOwnedBy($postId, $user['id'])) {
            return true;
        }
        else{
            $this->Flash->error('No eres el dueño de ese post');
            return false;
        }
    }

    return parent::isAuthorized($user);
}
    
    public function add(){
        $this->layout= "test";
        if($this->request->is('post')){
            $this->Post->create();
            $this->request->data['Post']['user_id'] = $this->Auth->user('id');
            if($this->Post->save($this->request->data)){                                    #Save: check for validation errors and abort save if errors occur
   
                $this->Flash->success('El post se ha publicado correctamente');    
                
                return $this->redirect(array('action' => 'index'));                         
            }
            $this->Flash->error('No se pudo añadir el post.');
        }
    }
    
    public function edit($id = null){
        $this->layout= "test";
        if (!$id) {
            throw new NotFoundException(__('Post inválido. (EDIT ID NULL)'));
        }
        $post = $this->Post->findById($id);
        if(!$post){
            throw new NotFoundException(__('Post inválido. (EDIT ID NOT FOUND)'));
        }
        
        if($this->request->is(array('post', 'put'))){
            $this->Post->id = $id;
            if ($this->Post->save($this->request->data)){                           #Check validation
                $this->Flash->success('El post con id: %s ha sido editado correctamente.', h($id));
                return $this->redirect(array('action'=>'index'));
            }
            $this->Flash->error('No se pudo actualizar el post con id: %s.', h($id));
        }
        
        if(!$this->request->data){
            $this->request->data = $post;
        }
    }
    
    public function delete($id){
        if($this->request->is('get')){
            throw new MethodNotAllowedException();
        }
        if($this->Post->delete($id)){
            $this->Flash->success(__('El post con id: %s ha sido eliminado.', h($id)));
        }
        else{
            $this->Flash->error(__('No se ha podido eliminar el post con id: %s .', h($id)));
        }
        
        return $this->redirect(array('action' => 'index'));
    }
}

用户 Controller

<?php

// app/Controller/UsersController.php
App::uses('AppController', 'Controller');

class UsersController extends AppController {

    public function beforeFilter() {
        parent::beforeFilter();
        //Allow users to register and logout
        $this->Auth->allow('add', 'logout');
    }
    
    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->Flash->success('Logeado correctamente');
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

    public function logout() {
        return $this->redirect($this->Auth->logout());
    }

    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->findById($id));
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Flash->success(__('The user has been saved'));
                return $this->redirect(array('controller' => 'pages', 'action' => 'inicio'));
            }
            $this->Flash->error(
                __('The user could not be saved. Please, try again.')
            );
        }
    }

    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Flash->success(__('The user has been saved'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Flash->error(
                __('The user could not be saved. Please, try again.')
            );
        } else {
            $this->request->data = $this->User->findById($id);
            unset($this->request->data['User']['password']);
        }
    }

    public function delete($id = null) {
        // Prior to 2.5 use
        // $this->request->onlyAllow('post');

        $this->request->allowMethod('post');

        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Flash->success(__('User deleted'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Flash->error(__('User was not deleted'));
        return $this->redirect(array('action' => 'index'));
    }

}

索引.ctp

<!-- File: /app/View/Posts/index.ctp -->                                                           

<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class ="jumbotron text-center">
    <h1>Twitter 2</h1>
</div>

<div class="container">
    <?php echo $this->Flash->render(); ?>
    
    <div class="row">
        
        <div class="col-sm-2">
        <?php echo $this->Html->link($this->Html->tag('span','',['class' => 'glyphicon glyphicon-plus']).' Add Post',
                array('controller' => 'posts', 'action' => 'add'),
                array('class' => 'btn btn-success btn-lg', 'role' => 'button', 'escape' => false)
        ); ?>  
        </div>
        
        <div class ="col-lg-10">
            <table class="table table-striped">
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Action</th>
                    <th>Author</th>
                    <th>Created</th>
                </tr>

                <!-- Here is where we loop through our $posts array, printing out post info -->

                <?php foreach ($posts as $post):?>
                <?php echo print_r($post); echo "<br>";?>
                <tr>
                    <td><?php echo $post['Post']['id']; ?></td>
                    <td>
                        <?php echo $this->Html->link($post['Post']['title'],                                    
                               array('controller' => 'posts', 'action' => 'view', $post['Post']['id']));
                        ?>     
                    </td>

                    <td>
                        <?php echo $this->Html->link($this->Html->tag('span','',['class' => 'glyphicon glyphicon-pencil']).' Editar',                                   
                               array('controller' => 'posts', 'action' => 'edit', $post['Post']['id']),
                                array('class' => 'btn btn-warning btn-sm', 'role' => 'button' , 'escape' => false)
                                );
                        ?>    
                        &nbsp
                        &nbsp
                        <?php echo $this->Form->postLink($this->Html->tag('span','',['class' => 'glyphicon glyphicon-trash']).' Eliminar'
                               array('controller' => 'posts', 'action' => 'delete', $post['Post']['id']), 
                                array('class' => 'btn btn-danger btn-sm', 'role' => 'button' , 'confirm' => '¿Estás seguro de que quieres eliminar este post?', 'escape' => false));
                        ?>     
                    </td>
                    
                    <td>
                        <?php echo $post['Post']['user_id']; ?>
                    </td>
                    
                    <td>
                        <?php echo $post['Post']['created']; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php unset($post); ?>
            </table>
        </div>
    </div>
</div>

帖子表

DROP TABLE IF EXISTS `posts`;
CREATE TABLE IF NOT EXISTS `posts` (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `body` text,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  `user_id` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

用户表

DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(20) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

PostModel取消注释$hasOne = "Users" 然后,在您看来, $post['Post']['user']['username']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM