プログラム言語 データベース操作 ORM

データ取得

データ型
use App\Models\Test;
$tests = Test::all();

モデルクラスのインスタンスを要素とするコレクションを取得

$tests = DB::table('テーブル物理名')–>get();

配列を取得

protected $modelClass = ‘Tests’;
$tests = $this–>Tests–>find()–>all();

モデルクラスのインスタンスを要素とするコレクションを取得

FROM
use App\Models\Test;
$tests = Test::all();

別名
$tests = Test::from('tests as t')–>all();

$tests = DB::table('テーブル物理名 as t')–>get();

別名
$tests = DB::table('テーブル物理名')–>get();

全件
use App\Models\Test;
$tests = Test::all();
$tests = DB::table('テーブル物理名')–>get();
protected $modelClass = ‘Tests’;
$tests = $this–>Tests–>find()–>all();

$testsTable = $this–>getTableLocator()–>get('Tests');
$tests = $testsTable–>find()–>all();

db = require('〜/models/index');

db.Model.findAll()
 .then(models => {
  console.log(models);
 });

先頭
$tests = Test::first();
Eloquentと同じ
$tests = $this–>Tests–>find()
 –>first();
末尾
$tests = Test::last();
Eloquentと同じ
$tests = $this–>Tests–>find()
 –>last();
N件
$tests = Test::take(10);
Eloquentと同じ
$tests = $this–>Tests–>find()
 –>limit(10);
存在チェック
$isExist = Test::exists();
ture/false
Eloquentと同じ
COUNT
$tests = Test::count();

 結合先テーブルのレコード数
 –>withCount('モデルクラス名');

$tests = Test::table(〜)–>count();
$tests = $this–>Tests–>find()
 –>count();
SUM
$tests = Test::get->sum(列名);
$query = $this–>Tests
 –>find()
 –>where([
  〜
 ]);

$test = $query–>select([
 '定義名' => $query–>func()–>sum('列名'),
])
–>first();

MAX
$max = Test::max('列名');
$max:5
Eloquentと同じ
値のみ
$tests = Test::pluck('列名');

結果 $tests = [1, 2, 3, 4, 5];

Eloquentと同じ
$tests = $this–>Tests–>find()
 –>select(['列名'])
 –>enableHydration(false)
 –>all()
 –>extract('列名')
 –>toList();

結果 $tests = [1, 2, 3, 4, 5];

SELECT
$tests = Test::select('列名')
 –>addSelect(〜);
Eloquentと同じ

WHERE

=
$tests = Test::where('列名', 100)
 –>where('列名', XXX) And条件
 –>orWhere('列名', XXX) Or条件
 –>get();

$tests = Test::where('列名', '<>', 100) 否定 ※!=はダメ
 –>get();

$tests = Test::whereRaw('列名 = 100')–>get();

Eloquentと同じ
$tests = $this–>Tests–>find()
 –>where([
  '列名' => 100,
  '列名' => XXX, And条件
 ]);
 –>andWhere([
  '列名' => 100,
 ]);
 –>orWhere([
  '列名' => 100,
 ]);
 –>all();
db = require('〜/models/index');

db.Model.findAll({
  where: {
   id: 〜
  }
 }).then(models => {
  console.log(models);
 });

db.Model.findByPk(〜)
 .then(model => {
  console.log(model);
 });

IN/NotIN
$tests = Test::whereIn('列名', [100, 200, 300])
 –>whereNotIn('列名', [100, 200, 300])
 –>get();
$tests = DB::table('テーブル物理名')
 –>whereIn('列名', [100, 200, 300])
 –>whereNotIn('列名', [100, 200, 300])
 –>get();
$tests = $this–>Tests–>find()
 –>where([
  '列名 IN' => [100, 200, 300],
 ]);
 –>all();
BETWEEN
$tests = Test::whereBetween('列名', [100, 200])
 –>get();
$tests = DB::table('テーブル物理名')
 –>whereBetween('列名', [100, 200])
 –>get();
$tests = $this–>Tests–>find()
 –>where(function ($exp) {
  $timestamp = FrozenTime::now()->subDay(1);

  return $exp->between(
   'Tests.created',
   $timestamp->startOfDay()->toDateTimeString(),
   $timestamp->endOfDay()->toDateTimeString()
  );
 })
 –>all();

NULL判定
$tests = Test::whereNull(列名)
->orWhereNull(列名); OR条件
->whereNotNull(列名); AND条件
->orWhereNotNull(列名); OR条件
->get();
Eloquentと同じ
A AND (B OR C)
$tests = Test::where(function($query){
 return $query
  ->where(〜)
  ->orWhere(〜);
})
->get();
Eloquentと同じ
LIKE
 $tests = Test::where('列名', 'LIKE', "%検索語%")
  –>get();

 $tests = Test::where('列名', 'NOT LIKE', "%検索語%")
  –>get();

Eloquentと同じ

GROUPBY

 $tests = Test::groupBy('列名')
  –>get();
Eloquentと同じ

JOIN

INNER JOIN
use App\Models\Test;
$tests = Test::with('結合先テーブルクラス名')–>all();

$tests = Test::with(['結合先テーブルクラス名' => function($query){
 $query->where('結合先テーブル列名', ‘LIKE’, ‘%〜%’);
}])->get(),

↓は可能だがEager Loadingを使用しない為にメリット無し
$tests = Test::join(
 '結合先テーブル物理名',
 '結合先テーブル物理名.列名', '=', 'テーブル物理名.列名'
)
–>get();

結果
foreach($tests as $t){
 $t–>結合先テーブルクラス名–>〜;
}

【単一条件】
$tests = DB::table('テーブル物理名')
 –>join(
  '結合先テーブル物理名',
  '結合先テーブル物理名.列名', '=', 'テーブル物理名.列名'
 )
 –>get();

結果
foreach($tests as $t){
 $t–>結合先テーブルクラス名–>〜;
}

【複数条件】
$tests = DB::table('テーブル物理名')
 ->join('結合先テーブル物理名', function($join){
  $join->on('結合先テーブル物理名.列名', '=', 'テーブル物理名.列名')
   ->where('結合先テーブル物理名.列名', '=', 'テーブル物理名.列名'));
 })
 –>get();

リレーション定義済の場合
$tests = $this–>Tests
 –>contain([
  '結合先テーブルクラス名1',
  '結合先テーブルクラス名2',
  結合先と更に結合
  '結合先テーブルクラス名3' =;> [
   '結合先テーブルクラス名4',
  ],
  結合条件指定
  '結合先テーブルクラス名5' =;> function (Query $query) use ($test) {
   return $query->where(['結合先テーブルクラス名5.列名' =;> $test->id]);
  },
 ])
 –>find()–>all();

結果
foreach($tests as $t){
 $t–>結合先テーブル名–>〜;
}

結合先テーブルのデータは取得しない場合1
$tests = $this–>Tests
 –>innerJoinWith('結合先テーブルクラス名6')
 –>innerJoinWith('結合先テーブルクラス名7', function ($q) use ($test) {
  return $q
   –>where(['結合先テーブルクラス名7.列名' =;> $test->id]);
 })
 –>find()–>all();

結合先テーブルのデータは取得しない場合2
$tests = $this–>Tests
 –>join()
  'table' => 'テーブル物理名',
  'alias' => 'テーブル別名',
  'type' => 'INNER',
  'conditions' => 'テーブル別名.列名 = 結合元テーブル名.列名',
 –>find()–>all();

LEFT JOIN
use App\Models\Test;
$tests = Test::leftJoin(
  '結合先テーブル物理名',
  '結合先テーブル物理名.列名', '=', 'テーブル物理名.列名'
 )
 –>get();

結果
foreach($tests as $t){
 $t–>結合先テーブルクラス名–>〜;
}

$tests = DB::table('テーブル物理名')
 –>leftJoin(
  '結合先テーブル物理名',
  '結合先テーブル物理名.列名', '=', 'テーブル物理名.列名'
 )
 –>get();

結果
foreach($tests as $t){
 $t–>結合先テーブルクラス名–>〜;
}

リレーション定義済の場合
$tests = $this–>Tests
 –>contain([
  〜
 ])
 –>find()–>all();

結合先テーブルのデータは取得しない場合1
$tests = $this–>Tests
 –>leftJoinWith('結合先テーブルクラス名6')
 –>leftJoinWith('結合先テーブルクラス名7', function ($q) use ($test) {
  return $q
   –>where(['結合先テーブルクラス名7.列名' =;> $test->id]);
 })
 –>find()–>all();

結合先テーブルのデータは取得しない場合2
$tests = $this–>Tests
 –>join()
  'table' => 'テーブル物理名',
  'alias' => 'テーブル別名',
  'type' => 'LEFT',
  'conditions' => 'テーブル別名.列名 = 結合元テーブル名.列名',
 –>find()–>all();

結合先テーブルのデータも取得する場合
$tests = $this–>Tests
 –>matching('結合先テーブルクラス名8')
 –>matching('結合先テーブルクラス名8', function ($q) use ($test) {
  return $q
   –>where(['結合先テーブルクラス名8.列名' =;> $test->id]);
 })
 –>find()–>all();

結果
foreach($tests as $t){
 $t–>_matchingData['結合先テーブルクラス名']–>〜;
}

has/doesnt
use App\Models\Test;
$tests = Test::has('結合先テーブル物理名')
 –>orHas('結合先テーブル物理名')
 –>whereHas(function($query){
  return $query–>where(〜);
 })
 –>get();

$tests = Test::doesntHave('結合先テーブル物理名')
 –>orDoesntHave('結合先テーブル物理名')
 –>whereDoesntHave(function($query){
  return $query–>where(〜);
 })
 –>get();

ORDER BY

$tests = Test::orderBy(列名, 'ASC')
 ->orderBy(列名, 'DESC')
 ->get();
Eloquentと同じ

サブクエリ

SELECT句
use App\Models\Test;
$tasks = Test::leftJoin(〜)
 ->leftJoin(〜)
 ->select()
 ->selectSub(
   use App\Models\TestMany;
  TestMany::selectRaw('count(*)')
   ->whereRaw('副問い合わせ先テーブル名.列名 = 〜.id')
  , 'SubCount')
 ->get();

※with(EargerLoading)を用いてのサブクエリは調査中

FROM句
use App\Models\Test;
$subquery = Test::select([
 DB::raw('IFNULL(col1, id) AS col1'),
 'col2',
])
->toSql();

$counts = DB::table(DB::raw("(${subquery}) AS counts"))
 ->select([
  'counts.col1',
  DB::raw('SUM(counts.col2) AS col2'),
 ])
 ->groupBy('counts.col1')
 ->get();

JOIN
use App\Models\TestMany;
$subQuery = DB::table(〜)
 ->where(〜, 555);

use App\Models\Test;
$tasks = Test::leftJoin(
  DB::raw("($subQuery->toSql()) AS SubTable", 'SubTable.列名', '=', 'tests.id')
 )
 サブクエリのバインディングをここで指定
 ->mergeBindings($subQuery)
 ->get();

データ更新

INSERT
【方法1 インスタンス作成→保存】
$user = new User();
$user->fill([
 'name' => 'Laravel',
 'email' => 'laravel@php.com'
]);

↓も可
$user->name = 'Laravel';
$user->email = 'laravel@php.com';

$user->save();

【方法2 インスタンス作成&保存】
$user = User::create([
 'name' => 'Laravel',
 'email' => 'laravel@php.com'
]);

【複数件INSERT】
User::createMany(
 [
  'name' => 'Laravel',
  'email' => 'laravel@php.com'
 ],
 [
  〜
 ]
);

DB::table('テーブル物理名')->insert([
 '列名' => 値,
 '列名' => 値,
]);

主キー取得
$id = DB::table('テーブル物理名')->insertGetId([
 '列名' => 値,
 '列名' => 値,
]);

db = require('〜/models/index');

db.Model.create({
 col1: 〜,
 col2: 〜,
 col3: 〜
})
.then(model => {
 console.log(model); 
});

UPDATE
$user = User::findOrFail(10);

$user->name = 'Laravel';
$user->email = 'laravel@php.com';

$user->save();

User::where(〜)
 ->update([
  '列名' => 値,
  '列名' => 値,
 ]);

db = require('〜/models/index');

db.Model.update({
 col1: 〜,
 col2: 〜,
 col3: 〜
},
{
 where: {
  id: 〜
 }
})
.then(model => {
 console.log(model); 
});

db.Model.findByPk(〜)
 .then(model => {
  model.col1 = 〜;
  model.col2 = 〜;
  model.col3 = 〜;
  model.save()
   .then(model => {
    console.log(model); 
   });
 });

UpdateOrCreate
User::UpdateOrCreate(
 [
  '更新対象検索条件列名' => 値,
  '更新対象検索条件列名' => 値,
 ],
 [
  '更新列名' => 値,
  '更新列名' => 値,
 ],
);
DELETE
【1件削除】
User::destroy(1);

【複数件削除】
User::where('name', 'Laravel')->delete();

db = require('〜/models/index');

db.Model.destroy({
 where: {
  id: 〜
 }
})
.then(model => {
 console.log(model); 
});

ATTACH
多対多のリレーションレコードを挿入
$user = User::find(1);

usersとrolesとの中間テーブルにroles.id=999のレコードを挿入
$user->roles()->attach(999);

挿入時の中間テーブルレコードを作成
$user->roles()->attach(999, ['expires' => $expires]);

DETTACH
usersとrolesとの中間テーブルからroles.id=999のレコードを削除
$user->roles()->detach(999);

全て削除
$user->roles()->detach();