2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Eloquent を単体で使うスニペット

Posted at

諸般の事情により Laravel に入門したので、Eloquent で素振りというか試し切りをするために単体で使えるようにするためのスニペット。普通にやろうとすると Application クラスやらが必要だったりめんどくさいので PDO のインスタンスから雑に使う方法。


illuminate/database をインストールします。

composer require illuminate/database

Connection を作成して Model にセットします。

<?php
require __DIR__ . '/vendor/autoload.php';

use Illuminate\Database\MySqlConnection;
use Illuminate\Database\ConnectionResolver;
use Illuminate\Database\Eloquent\Model;

$host = '192.168.99.100';
$port = 3306;
$database = 'test';
$username = 'root';
$password = '';

$pdo = new PDO("mysql:host=$host;port=$port;dbname=$database", $username, $password, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => 0,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$conn = new MySqlConnection($pdo);

$resolver = new ConnectionResolver([$conn]);
$resolver->setDefaultConnection(0);
Model::setConnectionResolver($resolver);

データベースを準備します。

<?php
$sql = <<<SQL
drop table if exists users;
drop table if exists groups;

create table groups (
    id int not null primary key auto_increment,
    name varchar (100)
);

create table users (
    id int not null primary key auto_increment,
    group_id int not null,
    name varchar (100)
);

insert into groups values
    (100, 'A'),
    (200, 'B'),
    (300, 'C');

insert into users (group_id, name) values
    (100, 'ore'),
    (100, 'are'),
    (200, 'sore'),
    (200, 'dore'),
    (300, 'kore'),
    (300, 'more');
SQL;
Model::getConnectionResolver()->connection()->unprepared($sql);

モデルクラスを定義して使ってみます。

<?php
class User extends Model
{
    public $timestamps = false;

    public function group()
    {
        return $this->belongsTo(Group::class);
    }
}

class Group extends Model
{
    public $timestamps = false;

    public function users()
    {
        return $this->hasMany(User::class);
    }
}

var_dump(User::query()->first()->group->toArray());
//=> [ 'id' => 100, 'name' => 'A' ]
2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?