CakePHP4のメモ
![]() |
13 |
560 views
コマンドプロンプトを起動して以下を実行しましょう。
create database samplepost;
データベースの接続情報を設定するために、config/app.phpファイルを編集します。以下のように、Datasources配列内に接続情報を設定します。
'Datasources' => [
'default' => [
'className' => Cake\Database\Connection::class,
'driver' => Cake\Database\Driver\Mysql::class,
'persistent' => false,
'host' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'samplepost',
'encoding' => 'utf8mb4',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
],
],
CakePHP4では、マイグレーションを使用してデータベースのテーブルを作成することができます。
以下は、Postsテーブルを作成するためのマイグレーションファイルの例です。
まず、以下のコマンドを実行して、Postsテーブルを作成するためのマイグレーションファイルを作成します。
bin\cake bake migration CreatePosts
このコマンドを実行すると、config/Migrationsディレクトリ内に、CreatePostsという名前のマイグレーションファイルが作成されます。
次に、マイグレーションファイルを編集して、Postsテーブルを作成します。
以下は、編集後のマイグレーションファイルの例です。
// config/Migrations/20220317123456_CreatePosts.php
declare(strict_types=1);
use Migrations\AbstractMigration;
class CreatePosts extends AbstractMigration
{
public function up(): void
{
$table = $this->table('posts');
$table
->addColumn('title', 'string', ['limit' => 255, 'null' => false])
->addColumn('body', 'text', ['null' => false])
->addColumn('created', 'datetime', ['null' => false])
->addColumn('modified', 'datetime', ['null' => false])
->create();
}
public function down(): void
{
$this->table('posts')->drop()->save();
}
}
このマイグレーションファイルでは、up()メソッドでpostsテーブルを作成しています。
addColumn()メソッドで、title、body、created、modifiedの4つのカラムを定義しています。
最後に、マイグレーションを実行して、Postsテーブルを作成します。以下のコマンドを実行してください。
bin\cake migrations migrate
以下のコマンドを実行して、View、Controller、Model、Entityファイルを自動生成します。
bin\cake bake all Posts
http://localhost/samplepost/posts/
にアクセスしてみましょう。
掲示板が出来上がっています。
Page 4 of 34.
1.php_xdebug-3.0.4-8.0-vs16-x86_64.dll
すぺぺぺ
本サイトの作成者。
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
ChatGPTで自動プログラム作成に取り組み中。
https://www.osumoi-stdio.com/novel/