如何在laravel 5.3 ORM中调用mysql存储过程使用参数

时间:2017-01-14 17:03:25

标签: php laravel-5

我创建了一个名为new_user的存储过程并对其进行了测试,当我在续集专业版和工作台中进行调用时工作正常。

我现在尝试使用laravel 5.3调用存储过程。我使用laravel insert create function进行了测试,它工作正常,这告诉我已经正确设置了laravel ORM。

然后我用google搜索了laravel网站doc并查看了一些stackoverflow解决方案并尝试实现它,但似乎没有工作。这是我到目前为止所尝试的内容

模型php非常简单

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel {
   protected $table = null;
}

在另一个班级我使用了以下功能

 $user = new \App\Models\Model;
//this calls but nothing gets inserted into the database
 $user::select('call new_user("myemail@test.com","mypassword","myname","mysurname");');

//same thing happens but nothing gets inserted into the database
     $user::select($user::raw('call new_user("myemail@test.com","mypassword","myname","mysurname");'));

 // this makes slim 3 throw BadMethodCallException
    $user::statement('call new_user("myemail@test.com","mypassword","myname","mysurname");');

// this makes slim 3 throw BadMethodCallException
 $user::statement('call new_user(_email,_password,_name,_surname)values(?,?,?,?)',["myemail@test.com","mypassword","myname","mysurname"]);

现在我不确定如何调用存储过程。我只是想知道我做错了什么。谢谢你的帮助

2 个答案:

答案 0 :(得分:0)

您不需要模型类来调用存储过程。 请致电:

DB::statement('call new_user(?, ?, ?, ?)',["myemail@test.com","mypassword","myname","mysurname"]);

答案 1 :(得分:0)

除了原始statement功能之外,Laravel的Eloquent中没有本地方式。但是,您可以创建自己的基本模型,可以在您的用户模型中使用,如此

class MyModel extends Model {

    public static function callStoredProcedure($name, $arrayOfKeyValues) {

        $statement = '\'call $name("';  // call stored procedure by argument $name
        $arguments = implode('", "' $arrayOfKeyValues) . '")\''; // values are merged as string
        $statement .= $arguments;
        self::::statement($statement);
    }
}

并在您的userModel中调用它: class UserModel extends MyModel {

控制器中的

示例:

UserModel::callStoredProcedure($stored_procedure_name, $array_of_arguments)