如何使用 Eloquent (Laravel) 调用存储过程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44354611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:04:48  来源:igfitidea点击:

How to call Stored Procedure with Eloquent (Laravel)?

phpmysqllaravelstored-procedureseloquent

提问by Hassan Raza

There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

文档中没有提到如何使用 Eloquent 语法在 laravel 中调用 MYSQL 中的存储过程的标准过程。

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

我的意思是有什么方法可以借助雄辩的语法在 mysql 中调用存储过程,例如

$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

有什么方法可以使用纯雄辩的语法(纯雄辩的方式)从存储过程中调用和获取结果。

Thanks. Small examples are highly encouraged .

谢谢。强烈鼓励小例子。

回答by Akram Wahid

You cannot call stored procedure with eloquent. However you can use query builder approach in the following style.

你不能用 eloquent 调用存储过程。但是,您可以使用以下样式的查询构建器方法。

first import the following namespaces on top of the controller file or in the file where you want to call the Stored Procedure.

首先在控制器文件的顶部或要调用存储过程的文件中导入以下命名空间。

use Illuminate\Support\Facades\DB;
use Doctrine\DBAL\Driver\PDOConnection;

then you can call the stored procedure like below,

然后你可以像下面一样调用存储过程,

$queryResult = $db->prepare('call searchAttendance(?,?,?,?,?)'); 
$queryResult->bindParam(1, $start_date); 
$queryResult->bindParam(2, $end_date); 
$queryResult->bindParam(3, $nurseRoles,PDOConnection::PARAM_STR); 
$queryResult->bindParam(4, $leaveTypesDayOffIds,PDOConnection::PARAM_STR); 
$queryResult->bindParam(5, $leaveTypesVactionIds,PDOConnection::PARAM_STR); 
$queryResult->execute(); 
$results = $queryResult->fetchAll(PDOConnection::FETCH_ASSOC); 
$queryResult->closeCursor(); 
return $results;

reference: Click here

参考:点击这里

回答by whoacowboy

As everyone has mentioned, you can't call a stored procedure in Laravel with Eloquent syntax. You can transfer the result of your query to a collectionwhich will give you all of the collection functionality.

正如每个人都提到的,您不能使用 Eloquent 语法在 Laravel 中调用存储过程。您可以将查询结果传输到一个集合该集合将为您提供所有集合功能。

$queryResult = DB::select('call my_custom_procedure(?, ?)', [1,2]);

$result = collect($queryResult);

return view('welcome')->with('result',$result);

回答by Abderrahim Soubai Elidrissi

No there is no Facadefor that a simple solution is to use a raw SQLquery

不,没有Facade一个简单的解决方案是使用原始SQL查询

$result = DB::select('my_custom_procedure(?, ?)', [1,2]);