LoginSignup
2
3

More than 5 years have passed since last update.

cakephp 2.x model 作成・書き方

Posted at

cakephp 2.xでModelの書き方が忘れがちなので記載しておきます。
あくまでも私のやりかた。

1.Modelフォルダにphpファイルを作成する。
任意の名前で使用できるので、わかりやすい名前にしています。
SQL上のテーブル名はxxxxx_usersという名前だった場合、cakephpではusersだけで問題ないならUsers.phpを作成する。

2.Users.phpの中身

Users.php
<?php
class Users extends AppModel {

»-public $useTable = "xxxxx_users";
»-public $primaryKey = 'no';

}

classはファイル名、class名がSQLのテーブル名と同じ場合は下記設定はいらない。
useTable → 割り当てるテーブル名
primaryKey → プライマリキー

プライマリキーは設定しておかないと、検索時に失敗します。

3.Contollerに記載する。

UsersContller.php
<?php
App::uses('AppController', 'Controller');

class UsersController extends AppController {
  public $uses = array(
    'Users'
  );

function indexの中身を書く前に上記のpublicを追加する。
array内にこのコントローラー内に使用したいテーブル名を追記していく。

2
3
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
2
3