0
0

More than 1 year has passed since last update.

Chapter5 クエリビルダ(5-3)

Posted at

クエリビルダとは?

SQL文にパラメータ配列の値を組み込んで文を生成するため、
正しくSQL文ができているかわかりにくい。
渡される値によっては、予想外のSQL文が実行される危険もあります。

そこで、用意されたのが、 「クエリビルダ」 です。
「クエリビルダ」 は、SQLのクエリ文を生成するために用意された一連のメソッドです。

DB::tableとget

早速クエリビルダを使ってみます。

HelloController.php
public function index(Request $request) {

        $items = DB::table('people')->get();

        return view('hello.index',['items' => $items]);
}
sample.php
$変数 = DB::table('**テーブル名**')->get();

指定したテーブルのビルダを取得します。
ビルダは「Illuminate\database\Query」名前空間にある Builderクラス で、
SQLクエリ文を生成するための機能を提供します。

ここではビルダの「get」メソッドを使っています。
これはそのテーブルにあるレコードを取得するもので、
SQLの select文に相当するものと考えていいでしょう。

例えば、get(['id','name'])とすれば、
idとnameのフィールドだけを取り出すことができます。
(省略すると全てのレコードの項目が取得できる。)

指定したIDのレコードを得る

参照用のテンプレートページを作成

show.php
@extends('layouts.helloapp')

@section('title','Show')

@section('menubar')
    @parent
    新規作成ページ
@endsection

@section('content')

    <form action="/hello/show" method="post">

        <table>

            <tr><th>id: </th><td>{{$item->id}}</td></tr>
            <tr><th>name: </th><td>{{$item->name}}</td></tr>
            <tr><th>mail: </th><td>{{$item->mail}}</td></tr>
            <tr><th>age: </th><td>{{$item->age}}</td></tr>

        </table>

    </form>

@endsection

@section('footer')
    copyright 2020 tuyano.
@endsection
HelloController.php
public function show(Request $request) {

        $id = $request->id;
        $item = DB::table('people')->where('id', $id)->first();

        return view('hello.show', ['item' => $item]);

}
web.php
Route::get('hello/show','App\Http\Controllers\HelloController@show');

演算記号を指定した検索

sample.php
where(**フィールド名**,**演算記号**,**** )
show.php
@section('content')

    @if($items != null)

        @foreach($items as $item)

            <table width="400px">

                <tr>
                    <th width="50px">id: </th><td width="50px">{{$item->id}}</td>
                    <th width="50px">name: </th><td width="50px">{{$item->name}}</td>
                </tr>

            </table>

        @endforeach

    @endif

@endsection
HelloController.php
public function show(Request $request) {

        $id = $request->id;
        $items = DB::table('people')->where('id', '<=', $id)->get();

        return view('hello.show', ['items' => $items]);
}

whereとorWhere

全ての条件に合致するものだけ検索

sample.php
where(**条件**)->where(**条件**)

条件に1つでも合致すれば全て検索

sample.php
where(**条件**)->orWhere(**条件**)

nameとmailから検索する

HelloController.php
public function show(Request $request) {

        $name = $request->name;
        $items = DB::table('people')
            ->where('name', 'like', '%' . $name . '%')
            ->orWhere('mail', 'like', '%' . $name . '%')
            ->get();

        return view('hello.show', ['items' => $items]);

}

上記の記述より、
クエリ文字の名前が「名前とメールアドレス」の中に入っているレコードに対して
全て検索する。

whereRawによる条件検索

sample.php
whereRaw(**条件式**,**パラメータ配列**)

並び順を指定する「orderBy」

sample.php
orderBy(**フィールド名**,'ascまたはdesc')
HelloController.php
public function index(Request $request) {

        $items = DB::table('people')->orderBy('age','asc')->get();

        return view('hello.index',['items' => $items]);
}

上記の記述をすることで、
indexページの並び順を年齢の昇順にする。

offsetlimit

指定した位置からレコードを取得する

offset(**整数**)

指定した数だけレコードを取得する

limit(**整数**)
HelloController.php
public function show(Request $request) {

        $page = $request->page;
        $items = DB::table('people')
            ->offset($page * 3)
            ->limit(3)
            ->get();

        return view('hello.show', ['items' => $items]);
}

insertによるレコード追加

sample.php
DB::table( **テーブル名**)->insert(**データをまとめた配列**)

レコード追加処理を変更する

HelloController.php
public function create(Request $request) {

        $param = [

            'name' => $request->name,
            'mail' => $request->mail,
            'age' => $request->age,

        ];
        DB::table('people')->insert($param);

        return redirect('/hello');
}

updateによるレコード更新

sample.php
DB::table( **テーブル名**)->where(**更新対象の指定**)->update(**配列**)
HelloController.php
public function edit(Request $request) {

        $item = DB::table('people')
            ->where('id', $request->id)->first();

        return view('hello.edit',['form' => $item]);

}

public function update(Request $request) {

        $param = [

            'name' => $request->name,
            'mail' => $request->mail,
            'age' => $request->age,

        ];
        DB::table('people')
            ->where('id', $request->id)
            ->update($param);

        return redirect('/hello');

}

deleteによるレコード削除

sample.php
DB::table( **テーブル名**)->where(**更新対象の指定**)->delete()
HelloController.php
public function del(Request $request) {

        $item = DB::table('people')
              ->where('id', $request->id)->first();

        return view('hello.del',['form' => $item]);

}

public function remove(Request $request) {

        DB::table('people')
            ->where('id', $request->id)->delete();

        return redirect('/hello');

}

これで、クエリビルダによるCRUDの基本が扱えるようになりました。

0
0
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
0
0