使い方
use Illuminate\Support\Facades\DB;
# 例 DB::select('select * from テーブル名')
$items = DB::select('select * from people'); #この例ではpeopleテーブルを全て呼び出し
パラメータ結合
# 例 id検索
$param = ['id' => $request->id];
$items = DB::select('select * from people where id = :id', $param);
インサート
DB::insert(クエリ文, パラメータ配列);
viewにidを渡す
下記のようにするとurlにidを含めることができる
HogeController.php
public function edit(Request $request){
$params = ['id' => $request->id];
# select文でurlで指定したidデータを取得(今回はエラー処理していないのでidがなければコケる)
$item = DB::select('select * from people where id = :id', $params);
return view('hello.edit', ['form' => $item[0]]);
}
web.php
Route::get('/hoge/edit/{id}', 'HogeController@edit');
コントローラで['form' => $item[0]
をviewに渡しているので$form
が使える
view.blade.php
<table>
<form action="/hoge/edit" method="post">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{ $form->id }}">
<tr>
<th>name: </th>
<td><input type="text" name="name" value="{{ $form->name }}"></td>
</tr>
<tr>
<th>email: </th>
<td><input type="text" name="email" value="{{ $form->email }}"></td>
</tr>
<tr>
<th>age: </th>
<td><input type="text" name="age" value="{{ $form->age }}"></td>
</tr>
<tr>
<th></th>
<td><input type="submit" value="送信"></td>
</tr>
</form>
</table>
update
HogeController.php
public function update(Request $request){
$params = [
'id' => $request->id,
'name' => $request->name,
'email' => $request->email,
'age' => $request->age
];
DB::update('update people set name = :name, email = :email, age = :age where id = :id', $params);
return redirect('/hoge');
}
web.php
Route::post('/hoge/edit', 'HogeController@update');
show
public function show(Request $request){
$item = DB::table('people')->where('id',$request->id)->first();
return view('hello.show', ['item'=>$item]);
}
web.php
Route::get('/hoge/{id}', 'HogeController@show');
where orWhere
すべての条件に合致するものを検索
# where使い方
where()->where()
条件の1つでも合致するものを検索
# orWhere使い方
where(フィールド名, 演算記号, 値)->orWhere(フィールド名, 演算記号, 値)
例:
$items = DB::table('people')
->where('name', 'like', '%' . $name . '%')
->orWhere('email', 'like', '%' . $name . '%')
->get();
whereRaw
配列にいれた値で条件検索できる
# whereRaw使い方
whereRaw(条件式, パラメータ配列)
例:
$items = DB::table('people')
->whereRaw('age >= ? and age <= ?', [1, 30])->get();
orderBy
desc ascでソート
# 使い方
orderBy(フィールド名, 'asc又はdesc')
例:
$items = DB::table('people')->orderBy('age', 'desc')->get();
offset/limit
指定位置からレコード取得
offset(整数)
指定数だけレコードを取得
limit(整数)