前提・実現したいこと
namespaceとclassの理解が怪しい程度の初学者です。
inputに文字列を入力
→完全一致か前方一致か選択
→submit
→次のページで結果を表示
この流れをLaravelで実現したいと考えています。
見よう見まねでクエリースコープを使ってみたのですが、
getやfirstで取得できる配列が下のようになります。
完全一致でprint_r($items_arr)をした結果
App\Models\search Object ( [table:protected] => item [primaryKey:protected] => id [connection:protected] => mysql [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => xxx //期待どおりの値は習得できています [name] => xxxxx ) ......(続く) )
これを↓のように取得できないでしょうか。
Array ( [0] => Array ( [id] => xxx [0] => xxx [name] => xxxx [1] => xxxx ) [1] => Array ( [id] => xxx [0] => xxx [name] => xxxx [1] => xxxx ) )
なぜ$items_arrにオブジェクトが入っているのか見当がつきません。
DB::table('item')を入れていないからなのかとも思いましたが、
どのタイミングで指定すればいいのかわかりません。
protected $table = 'item';
で指定したのは何なんだろう…とも思ってしまいます。
該当のソースコード
index.twig
<div> <form action="list" method="post"> {{ csrf_field() }} <input type="text" name="input"> <select name="search_type"> <option value="perfect" selected>完全一致</option> <option value="fuzzy">を含む</option> </select> <button type="submit">検索</button> </form> </div>
app/Models/search.php
php
1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Model; 6 7class search extends Model 8{ 9 protected $table = 'item'; 10 protected $primaryKey = 'id'; 11 12 //完全一致 13 public function scopePerfect($query, $input) 14 { 15 return $query->where('id', $input); 16 } 17 18 //前方一致 19 public function scopeFuzzy($query, $input) 20 { 21 return $query->where('id', 'like', "$input%"); 22 } 23}
listController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\search; class listController extends Controller { public function store(Request $request) { //リクエスト内容 $conditions = $request; $md = new search(); switch($request->search_type){ case 'perfect': $items_arr = $md->Perfect($request->input)->first(); break; case 'fuzzy': $items_arr = $md->fuzzy($request->input)->get(); break; default: break; } echo '<pre>'; print_r($items_arr); echo '</pre>'; return view('list/list', compact( 'items_arr', 'conditions' ) ); } }
補足情報(FW/ツールのバージョンなど)
Laravel 5.6.3
PHP 7.1.8
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/16 09:43