一,得到最新的sql
-
DB::connection()->enableQueryLog();
//這裏爲查詢操作
-
dump(DB::getQueryLog());
上面方法參數不能直接打印出來,可以定義一個全局函數,然後將上面的 dump(DB::getQueryLog()) 替換成
dump(getRealSql(DB::getQueryLog()));
/**
* 打印完整Sql
*/
if (! function_exists('getRealSql')) {
/**
* @param $message
*/
function getRealSql($bindings)
{
$data = [];
foreach ($bindings as $k=> $b){
$bi = $b['bindings'];
$bi = array_map(function($a){
return '\''.$a.'\'';
},$bi);
$sql = str_replace('?', '%s', $b['query']);
$sql2 = sprintf($sql, ...$bi);
$data[$k] = $sql2;
}
return $data;
}
}
二,更新表單數據
因爲含有_token
可以:
$data = request()->except(['_token']);
Model::where('id',$request->input('id'))->update($data);
也可以:
Model::find($request->input('id'))->update($request->all());
想要實現laravel多條件查詢 嵌套查詢:
SELECT
`price`
FROM
`fedexprices`
WHERE
( `profile` = 'FEDEX101' AND `service` = 'SMART_POST' AND `weight` = '50.0' AND `zone` = '2' )
AND ( `start_at` <= '2019-09-25' OR `start_at` IS NULL )
ORDER BY
`start_at` DESC
LIMIT 1
前面可以組裝成
$where = array(
['profile', '=', 'p'],
['service', '=', 's'],
['weight', '=', $totalWeight],
['zone', '=', $realZone]
);
需要嵌套的時候使用回調函數,回調函數相當於加個小括號在外面
$hasStartAt = Model::where($where)->where(function ($query) {
$query->where('start_at', '<=', date('Y-m-d'))
->orWhere('start_at', null);
})->select($select)->orderByDesc('start_at')->first();
##查詢另外的表的子查詢舉例
User::whereIn('id', function($query){
$query->select('user_id')
->from('admin_user')
->whereIn('type', ['1', '2']);
})->get();
參考:https://blog.csdn.net/xcqingfeng/article/details/80364618
三,在驗證後手動填值:
一般表單驗證後會自動存之前的數據,也可以手動更改,使用withInput,
return redirect()-> back()->withInput(['error'=>'註冊失敗,短信驗證碼不正確','page'=>'phone']);
頁面也可以用old展示
<input type="text" name="username" value="{{ old('error') }}">
四, 得到某個表格的所有字段:
Schema::getColumnListing('xxxxs');
Schema的命名空間: Illuminate\Support\Facades\Schema