0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CakePHPで便利なクエリビルダーを使ってみる

Posted at

対象読者

CakePHPでクエリビルダーを使ってみたい人

ソフトウェア環境

ソフトウェア バージョン
CakePHP 4.7.5
PHP 8.1

今回は、register関数でユーザー登録に成功したら、success関数内でセッションから取得したユーザーIDを使って
一意となるレコードをクエリビルダーで取得する処理です。

 $selectUsers = $selectUsersTable
                        ->find()
                        ->select(['id','name','username','password'])
                        ->where(['name'=>$targetName,'username'=>$targetEmail,'password'=>$targetPassword])->toList();

取得した1行のレコードは配列で返却されるのでこんな感じでビューに詰めています。

$selectUsers[0]->値
RegistersController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\ORM\TableRegistry;/*追加*/



/**
 * Registers Controller
 *
 * @method \App\Model\Entity\Register[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class RegistersController extends AppController
{       
    
    public function initialize(): void
    {
        parent::initialize();
        //companiesのDBを指定
        $this->usersTable = TableRegistry::get('users');
        //セッションをセットする
        $this->session = $this->getRequest()->getSession();
        //ページネーションで表示件数を指定
        $this->paginate['limit'] = 10;
    }
    ()

    public function register()
    {
        $this->request->is('post');
       
        $yourName = $this->request->getData('yourNAme');
        //debug($yourName);
        $email = $this->request->getData('yourEmail');
        $password = $this->request->getData('yourPassword');
        //debug($email); 確認したらデバッグコンソールはコメントアウト
        $this->set('id',$yourName);

        //データを買う脳するための対象テーブル情報を取得する
        $usersTable = TableRegistry::getTableLocator()->get('users');
        //エンティティを生成する。
        $newUsers = $this->usersTable->newEmptyEntity();
        //エンティティのカラム名に画面から取得したデータを渡す
        $newUsers->name = $yourName;
        $newUsers->username = $email;
        $newUsers->password = $password;
        $newUsers->role_id = 0;
        $newUsers->created = '2024-10-01';//modified
        $newUsers->modified = '2024-10-02';

        $this->session->write('visitedDate', date('H:i:s'));
        $this->session->write('targetName', $yourName);
        $this->session->write('targetEmail', $email);
        $this->session->write('targetPassword', $password);

        //テーブルへ登録する。
        $this->usersTable->save($newUsers);
        //return $this->response->withStringBody($yourName);
           
        return $this->redirect(['controller'=>'Registers','action' => 'success']);
        
    }

    public function success()
    {
        //セッションから値を取得する
        $targetName = $this->session->read('targetName');
        $targetEmail = $this->session->read('targetEmail');
        $targetPassword = $this->session->read('targetPassword');
        $visitedDate = $this->session->read('visitedDate');


        //Viewに値を設定する
        $this->set('targetName',$targetName);
        $this->set('visitedDate',$visitedDate);

        //テーブルからidに紐づくレコードを取得
        $selectUsersTable = TableRegistry::getTableLocator()->get('users');
        $selectUsers = $selectUsersTable
                        ->find()
                        ->select(['id','name','username','password'])
                        ->where(['name'=>$targetName,'username'=>$targetEmail,'password'=>$targetPassword])->toList();
        //1レコードのインデックス[0]を指定すること
        //dd($selectUsers[0]->name);


        $this->set('selectId',$selectUsers[0]->id);
        $this->set('selectName',$selectUsers[0]->name);
        $this->set('selectEmail',$selectUsers[0]->username);
        $this->set('selectPassword',$selectUsers[0]->password);

        $this->render();                                    
       
    }

        //ユーザー情報を更新する
    public function userInfoEdit()
    {
        //HTTPプロトコルがPOST通信であるかを判定
        $this->request->is('post');

        //IDを取得
        $getId = $this->request->getData('targetEditId');
        
        //自クラスの関数を呼び出す
        $targetUser = self::selectUserById($getId);
        //dd($targetUser[0]->name);

        $this->session->write('targetId', $targetUser[0]->id);
        $this->session->write('targetUser', $targetUser[0]->name);
        $this->session->write('targetUserName', $targetUser[0]->username);
        $this->session->write('targetPassword', $targetUser[0]->password);                            

        return $this->redirect(['controller'=>'Registers','action' => 'editok']);                                                      
    }
    
}

シンプルでこんなにラクにかけてしまうのは、とても良いですね🌝

参考になったらうれしいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?