プログラム言語 データベース操作 ORM
目次
データ取得
データ型
$tests = Test::all();
モデルクラスのインスタンスを要素とするコレクションを取得
配列を取得
$tests = $this–>Tests–>find()–>all();
モデルクラスのインスタンスを要素とするコレクションを取得
FROM
$tests = Test::all();
別名
$tests = Test::from('tests as t')–>all();
別名
$tests = DB::table('テーブル物理名')–>get();
全件
$tests = Test::all();
$tests = $this–>Tests–>find()–>all();
$testsTable = $this–>getTableLocator()–>get('Tests');
$tests = $testsTable–>find()–>all();
db.Model.findAll()
.then(models => {
console.log(models);
});
先頭
–>first();
末尾
–>last();
N件
–>limit(10);
存在チェック
COUNT
結合先テーブルのレコード数
–>withCount('モデルクラス名');
–>count();
SUM
–>find()
–>where([
〜
]);
$test = $query–>select([
'定義名' => $query–>func()–>sum('列名'),
])
–>first();
MAX
値のみ
結果 $tests = [1, 2, 3, 4, 5];
–>select(['列名'])
–>enableHydration(false)
–>all()
–>extract('列名')
–>toList();
結果 $tests = [1, 2, 3, 4, 5];
SELECT
WHERE
=
–>where('列名', XXX) And条件
–>orWhere('列名', XXX) Or条件
–>get();
$tests = Test::where('列名', '<>', 100) 否定 ※!=はダメ
–>get();
$tests = Test::whereRaw('列名 = 100')–>get();
–>where([
'列名' => 100,
'列名' => XXX, And条件
]);
–>andWhere([
'列名' => 100,
]);
–>orWhere([
'列名' => 100,
]);
–>all();
db.Model.findAll({
where: {
id: 〜
}
}).then(models => {
console.log(models);
});
db.Model.findByPk(〜)
.then(model => {
console.log(model);
});
IN/NotIN
–>whereNotIn('列名', [100, 200, 300])
–>get();
–>whereIn('列名', [100, 200, 300])
–>whereNotIn('列名', [100, 200, 300])
–>get();
–>where([
'列名 IN' => [100, 200, 300],
]);
–>all();
BETWEEN
–>get();
–>whereBetween('列名', [100, 200])
–>get();
–>where(function ($exp) {
$timestamp = FrozenTime::now()->subDay(1);
return $exp->between(
'Tests.created',
$timestamp->startOfDay()->toDateTimeString(),
$timestamp->endOfDay()->toDateTimeString()
);
})
–>all();
NULL判定
->orWhereNull(列名); OR条件
->whereNotNull(列名); AND条件
->orWhereNotNull(列名); OR条件
->get();
A AND (B OR C)
return $query
->where(〜)
->orWhere(〜);
})
->get();
LIKE
–>get();
$tests = Test::where('列名', 'NOT LIKE', "%検索語%")
–>get();
GROUPBY
JOIN
INNER JOIN
$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
$tests = Test::leftJoin(
'結合先テーブル物理名',
'結合先テーブル物理名.列名', '=', 'テーブル物理名.列名'
)
–>get();
結果
foreach($tests as $t){
$t–>結合先テーブルクラス名–>〜;
}
–>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
$tests = Test::has('結合先テーブル物理名')
–>orHas('結合先テーブル物理名')
–>whereHas(function($query){
return $query–>where(〜);
})
–>get();
$tests = Test::doesntHave('結合先テーブル物理名')
–>orDoesntHave('結合先テーブル物理名')
–>whereDoesntHave(function($query){
return $query–>where(〜);
})
–>get();
ORDER BY
->orderBy(列名, 'DESC')
->get();
サブクエリ
SELECT句
$tasks = Test::leftJoin(〜)
->leftJoin(〜)
->select()
->selectSub(
use App\Models\TestMany;
TestMany::selectRaw('count(*)')
->whereRaw('副問い合わせ先テーブル名.列名 = 〜.id')
, 'SubCount')
->get();
※with(EargerLoading)を用いてのサブクエリは調査中
FROM句
$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
$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
$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'
],
[
〜
]
);
'列名' => 値,
'列名' => 値,
]);
主キー取得
$id = DB::table('テーブル物理名')->insertGetId([
'列名' => 値,
'列名' => 値,
]);
db.Model.create({
col1: 〜,
col2: 〜,
col3: 〜
})
.then(model => {
console.log(model);
});
UPDATE
$user->name = 'Laravel';
$user->email = 'laravel@php.com';
$user->save();
User::where(〜)
->update([
'列名' => 値,
'列名' => 値,
]);
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
[
'更新対象検索条件列名' => 値,
'更新対象検索条件列名' => 値,
],
[
'更新列名' => 値,
'更新列名' => 値,
],
);
DELETE
User::destroy(1);
【複数件削除】
User::where('name', 'Laravel')->delete();
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
$user->roles()->detach(999);
全て削除
$user->roles()->detach();