部分一致での検索機能を実装したときのメモ
nameの部分一致の記述はjsonでの書き方をしていた時
model_numberの部分一致はSqlHelperってものを使えば便利であると教わったもの
この後nameも同様に書き換えた。
Item.Controller.php
<?php
namespace App\Http\Controllers;
use App\Helpers\SqlHelper;
use Illuminate\Http\Request;
use App\Models\MtItem;
class ItemController extends Controller
{
//商品検索
public function get(Request $request)
{
$query = MtItem::query();
if ($request->has('name')) {
$query->where('name', 'LIKE', '%'.$request->input('name').'%');
}
if ($request->has('jancd')) {
$query->where('jancd', 'LIKE', $request->input('jancd'));
}
if ($request->has('model_number')) {
$query->where('model_number', 'LIKE', SqlHelper::escapePartialMatch($request->input('model_number')));
}
$items = $query->get();
// 商品情報をJSON形式でレスポンスとして返す
return response()->json($items);
}
}
SqlHelper.php
<?php
namespace App\Helpers;
class SqlHelper {
/**
* 部分一致テキストへエスケープ
*/
public static function escapePartialMatch(string $value, string $char = '\\')
{
return '%'.str_replace(
[$char, '%', '_'],
[$char.$char, $char.'%', $char.'_'],
$value
).'%';
}
/**
* 前方一致テキストへエスケープ
*/
public static function escapePrefixMatch(string $value, string $char = '\\')
{
return str_replace(
[$char, '%', '_'],
[$char.$char, $char.'%', $char.'_'],
$value
).'%';
}
/**
* 前方一致テキストへエスケープ
*/
public static function escapeBackwardMatch(string $value, string $char = '\\')
{
return '%'.str_replace(
[$char, '%', '_'],
[$char.$char, $char.'%', $char.'_'],
$value
);
}
}
まとめ
SqlHelperクラスは、SQLクエリで使用するテキストをエスケープするためのヘルパークラスです。エスケープ処理を行うことで、特定の文字(例えば、'%', '_')がSQLで特別な意味を持つ文字として扱われることを防ぐ。