如何将参数传递给Laravel DB :: transaction() [英] How to pass parameter to Laravel DB::transaction()

查看:249
本文介绍了如何将参数传递给Laravel DB :: transaction()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从laravel文档中:数据库事务. 它说:

From the laravel documentation: Database Transaction. It says that:

DB::transaction(function() {
    DB::table('users')->update(array('votes' => 1));
    DB::table('posts')->delete();
});

在这里,显式输入1以更新用户... 我用一个变量试过了

Here, 1 is explicitly entered to update the users... I tried this using a variable,

$id = 3;
DB::transaction(function() {
    DB::table('users')->where('id','=',$id)->get();
});

它抛出一个错误:

Undefined variable: id

我还尝试将$ id放置为这样的参数:

I also tried to place to $id as a parameter like this:

$id = 3;
DB::transaction(function($id) {
    DB::table('users')->where('id', '=', $id)->get();
});

还是一个错误:

Illuminate \ Database \ MySqlConnection类的对象无法转换为字符串

Object of class Illuminate\Database\MySqlConnection could not be converted to string

我做错了什么吗?请指教.谢谢...

Have I done anything wrong? Please advise. Thanks...

推荐答案

您需要的是use关键字:

$id = 3;
DB::transaction(function($id) use ($id) {
    DB::table('users')->where('id', '=', $id)->get();
});

对于PHP 7(未经测试,根据以下答案的要求进行编辑):

For PHP 7 (untested, edited as requested by the answer below):

$id = 3;
DB::transaction(function() use ($id) {
    DB::table('users')->where('id', '=', $id)->get();
});

这篇关于如何将参数传递给Laravel DB :: transaction()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆