如何将参数传递给 Laravel DB::transaction()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17084723/
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
How to pass parameter to Laravel DB::transaction()
提问by Melvin
From the laravel documentation: Database Transaction. It says that:
来自 laravel 文档:数据库事务。它说:
DB::transaction(function() {
DB::table('users')->update(array('votes' => 1));
DB::table('posts')->delete();
});
Here, 1 is explicitly entered to update the users... I tried this using a variable,
在这里,显式输入 1 以更新用户...我尝试使用变量进行此操作,
$id = 3;
DB::transaction(function() {
DB::table('users')->where('id','=',$id)->get();
});
It throws an error:
它抛出一个错误:
Undefined variable: id
I also tried to place to $id as a parameter like this:
我还尝试将 $id 作为参数放置,如下所示:
$id = 3;
DB::transaction(function($id) {
DB::table('users')->where('id', '=', $id)->get();
});
Still, an error:
仍然,一个错误:
Object of class Illuminate\Database\MySqlConnection could not be converted to string
类 Illuminate\Database\MySqlConnection 的对象无法转换为字符串
Have I done anything wrong? Please advise. Thanks...
我做错了什么吗?请指教。谢谢...
回答by Alexandre Danault
The use
keyword is what you need:
该use
关键字是你所需要的:
$id = 3;
DB::transaction(function($id) use ($id) {
DB::table('users')->where('id', '=', $id)->get();
});
For PHP 7 (untested, edited as requested by the answer below):
对于 PHP 7(未经测试,按照以下答案的要求进行编辑):
$id = 3;
DB::transaction(function() use ($id) {
DB::table('users')->where('id', '=', $id)->get();
});
回答by o.v
In PHP 7 the syntax has changed:
在 PHP 7 中,语法发生了变化:
$id = 3;
DB::transaction(function () use ($id) {
DB::table('users')->where('id', '=', $id)->get();
});
回答by LeRoy
To answer @CaptainHypertext question of
回答@CaptainHypertext 的问题
If you alter $id inside the closure, will it affect the $id outside?
如果你在闭包内部修改 $id ,它会影响外部的 $id 吗?
This method worked for me:
这种方法对我有用:
$id = 3;
$transactionResult = DB::transaction(function($id) use ($id) {
$request_id = DB::table('requests')->insertGetId([
'company_id' => $company->$id,
]);
return $request_id ;
});
echo($transactionResult);