我只想对控制器内部的一个查询而不对整个laravel应用程序禁用MySQL严格模式,
我知道禁用MySQL严格模式的风险,所以我不想从config / database.php中为整个应用程序禁用它,
我在整个应用程序中只遇到一个查询,因此我想在我的控制器中禁用它,然后只运行一次查询!
请帮我解决给定情况。
答案 0 :(得分:4)
config()->set('database.connections.mysql.strict', false);
\DB::reconnect(); //important as the existing connection if any would be in strict mode
Model::select()->get(); // your query called in non strict mode
//now changing back the strict ON
config()->set('database.connections.mysql.strict', true);
\DB::reconnect();
答案 1 :(得分:1)
在config / database.php中,执行以下操作:
'connections'=> [
'mysql' => [
// Behave like MySQL 5.6
'strict' => false,
// Behave like MySQL 5.7
'strict' => true,
]
]
答案 2 :(得分:1)
将它用于≤5.7的MySQL(摘自here):
DB::statement("set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
// your query
DB::statement("set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
答案 3 :(得分:1)
您可以做的一件事就是在运行时更改此值
public function doQueryWithoutStrictMode{
config('database.connections.mysql.strict', false);
DB::select('The query you want to make, and that should work!');
And then, if you later want to do another query in strict mode withing the same
method you can enable it like this.
config('database.connections.mysql.strict', true);
DB::select('your other query with strict mode');
}