カテゴリー
db

Laminas dbの例(fetchOne的)laminas dbのselectを使う

itemテーブルの列数を取る

<?php
//autoloadの位置は適宜設定してください
require '../vendor/autoload.php';

use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Sql\Sql;

$db = new Adapter([
     'driver'   => 'Pgsql', //postgresを使う場合
     'host' => 'localhost',
     'database' => db名,
     'username' => ユーザID,
     'password' => パスワード
 ]);
$sql = new Sql($db);
$sel = $sql->select();
$sel->from('item');
$sel->columns(['num' => new \Laminas\Db\Sql\Expression('COUNT(*)')]);
$stm = $sql->prepareStatementForSqlObject($sel);
echo $stm->execute()->current()['num'];
カテゴリー
db

Laminas dbの例(fetchOne的)sqlベタ書き

テーブルの列数を取る例

<?php
//autoloadの位置は適宜修正してください
require '../vendor/autoload.php';

use Laminas\Db\Adapter\Adapter;

$db = new Adapter([
     'driver'   => 'Pgsql', //postgresを使う場合
     'host' => 'localhost',
     'database' => db名,
     'username' => ユーザID,
     'password' => パスワード
 ]);
 $stm = $db->createStatement("SELECT COUNT(*) FROM item");
 echo $stm->execute()->current()['count'];
カテゴリー
db

Laminas dbの例(fetchAll的)

日本語記事が意外と見つからないzend db的にはfetchAllに該当するサンプル

use Laminas\Db\Adapter\Adapter;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\Sql\Sql;

$sql = "SELECT * FROM item WHERE id = ?";
$statement = $adapter->createStatement($sql, [$id]);
$result = $statement->execute();
$items = new ResultSet;
$items->initialize($result);
$rows = $items->toArray();

プレイスホルダーも使えます。
$itemsの時点だとオブジェクトです。
toArrayでfetchAllの時のように配列になります。

driverによっては?(ハテナ・クエスチョン)が使えず$1..を使わないといけないかもしれません。
例えばドライバーがPgsqlだと、?が使えません。

zend1の時のように、短く書ける方法をご存じの方はお知らせくださいm(__)m

カテゴリー
db

Laminas dbのトランザクション

Laminas dbの公式のマニュアルにも見つけられないが、トランザクションは以下の方法で行えるようだ。


$adapter->getDriver()->getConnection()->beginTransaction();
$adapter->getDriver()->getConnection()->commit();
$adapter->getDriver()->getConnection()->rollback();

作成された最後のIDを取得することもできるみたい

$adapter->getDriver()->getConnection()->getLastGeneratedValue();

pgSQLを使用している場合は、最後に作成されたIDを返すシーケンスを追加する必要があるらしい。

$adapter()->getDriver()->getConnection()->getLastGeneratedValue(‘hoge_hogeid_seq’);

カテゴリー
db

laminas db insert

insert(挿入)

zend_dbのinsert文は簡単だったなぁ…


use Laminas\Db\Adapter\Adapter;
 
$db = new Adapter([
    'driver'   => 'Pdo_Pgsql', //postgresを使う場合
    'database' => 'データベース名',
    'username' => 'ユーザー名',
    'password' => 'ユーザーパスワード',
]);
$sql = new Sql($db);
$insert = $sql->insert("item");
$insert->values([
    'name' => 'test',
    'kosu' => 1
]);
$statement = $sql->prepareStatementForSqlObject($insert);
$results = $statement->execute(); 

もっと短く書ける方法をご存じの方はお知らせくださいm(__)m

カテゴリー
db

laminas dbの例(fetchRow的)

日本語記事が意外と見つからないサンプル

zendframeworkのZend_Db的なもの。
fetchRow的なもの。

select文(クエリーベタ書き)

use Laminas\Db\Adapter\Adapter;
 
 $db = new Adapter([
     'driver'   => 'Pdo_Pgsql', //postgresを使う場合
     'database' => 'データベース名',
     'username' => 'ユーザー名',
     'password' => 'ユーザーパスワード',
 ]);
 $statement = $db->createStatement("SELECT * FROM テーブル名 WHERE tel = ? AND address = ?", [$tel, $address]);
 $results = $statement->execute();
 $row = $results->current();
 $name = $row['name'];

Zend_Dbのように、もっとコード少なくて済む方法をご存じの方は教えてくださいm(__)m

カテゴリー
db

Getting Started with Laminas – Database and models

Laminasを使ってみる
データベースとモデル

データベース

Now that we have the Album module set up with controller action methods and view scripts, it is time to look at the model section of our application. Remember that the model is the part that deals with the application’s core purpose (the so-called “business rules”) and, in our case, deals with the database. We will make use of laminas-db’s Laminas\Db\TableGateway\TableGateway to find, insert, update, and delete rows from a database table.

We are going to use Sqlite, via PHP’s PDO driver. Create a text file data/schema.sql with the following contents:

CREATE TABLE album (id INTEGER PRIMARY KEY AUTOINCREMENT, artist varchar(100) NOT NULL, title varchar(100) NOT NULL);
INSERT INTO album (artist, title) VALUES ('The Military Wives', 'In My Dreams');
INSERT INTO album (artist, title) VALUES ('Adele', '21');
INSERT INTO album (artist, title) VALUES ('Bruce Springsteen', 'Wrecking Ball (Deluxe)');
INSERT INTO album (artist, title) VALUES ('Lana Del Rey', 'Born To Die');
INSERT INTO album (artist, title) VALUES ('Gotye', 'Making Mirrors');

(The test data chosen happens to be the Bestsellers on Amazon UK at the time of writing!)

Now create the database using the following:


module/Album/src/ModelにAlbumTable.phpを作る。

namespace Album\Model;

class Album
{
    public $id;
    public $artist;
    public $title;

    public function exchangeArray(array $data)
    {
        $this->id     = !empty($data['id']) ? $data['id'] : null;
        $this->artist = !empty($data['artist']) ? $data['artist'] : null;
        $this->title  = !empty($data['title']) ? $data['title'] : null;
    }
}

Laminas\Db\Adapter\AdapterInterfaceサービスはlaminas-dbコンポーネントによって登録されます。以前、config/modules.config.phpに次のエントリが含まれていることに気づいたかもしれません。:

return [
    'Laminas\Form',
    'Laminas\Db',
    'Laminas\Router',
    'Laminas\Validator',
    /* ... */
],

All Laminas components that provide laminas-servicemanager configuration are also exposed as modules themselves; the prompts as to where to register the components during our initial installation occurred to ensure that the above entries are created for you.

The end result is that we can already rely on having a factory for the Laminas\Db\Adapter\AdapterInterface service; now we need to provide configuration so it can create an adapter for us.

LaminasのModuleManagerは、各モジュールのmodule.config.phpファイルからすべてのconfigurationをマージしてからconfig/autoload/ (first *.global.php files, and then *.local.php files)にマージします。データベースconfiguration情報をバージョン管理システムにコミットすべきglobal.phpに追加します。必要に応じてlocal.php (バージョン管理システム外) にデータベースの資格情報を保存できます。 次のコードを使用してconfig/autoload/global.php(アルバムモジュール内ではなくプロジェクトルート内)を変更します。 :

return [
    'db' => [
        'driver' => 'Pdo',
        'dsn'    => sprintf('sqlite:%s/data/laminastutorial.db', realpath(getcwd())),
    ],
];
カテゴリー
db

laminasのtable gatewayを用いたdbの使用法のドキュメント

https://docs.laminas.dev/tutorials/getting-started/database-and-models/

カテゴリー
db

tableGateway関連説明サイト その2

zendframework3だと思われるtableGatewayが記述されたチュートリアル(公式)

https://docs.zendframework.com/tutorials/getting-started/database-and-models/

と、それを翻訳?したサイト

http://rakulack.net/archives/50

カテゴリー
db

tableGateway関連説明サイト

zendframework2だがzf3でも使えるtableGatewayを使ったzend-dbを使う方法?

http://blog.livedoor.jp/kazylla/archives/28530709.html