Php I';我无法在Laravel中使用事务

Php I';我无法在Laravel中使用事务,php,mysql,laravel,laravel-5.2,Php,Mysql,Laravel,Laravel 5.2,我正在和拉威尔一起做一个爱好项目(商店管理)。我试图使用DB::beginTransaction()和DB::rollback(),但它不起作用。根据我的代码,我认为数据库中不应该填充任何条目 我已经在谷歌上搜索过各种可能性,但找不到任何解决方案。 而且,我的MySQL表是InnoDB 这是我的店铺管理员档案 class shopController extends Controller { public function __construct() {

我正在和拉威尔一起做一个爱好项目(商店管理)。我试图使用DB::beginTransaction()和DB::rollback(),但它不起作用。根据我的代码,我认为数据库中不应该填充任何条目

我已经在谷歌上搜索过各种可能性,但找不到任何解决方案。 而且,我的MySQL表是InnoDB

这是我的店铺管理员档案

    class shopController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function getView()
    {
        if(Auth::user()->shop_status==0)
            return View::make('shop')->with('name',json_encode(Auth::user()->Vendor_Detail()->get(['first_name', 'last_name'])));
        else
            return redirect('/home');
    }

    public function addShop(ShopDataRequest $request){
    //get the logged in vendor's model instance. Auth uses Vendor model
            $vendor = Auth::user();
    //create new Shop Model
            $shop = new Shop;
            $shop->name = $request['shop_name'];
            $shop->address = $request->addressLine1;
            $shop->pincode = $request->pincode;
            $shop->phone = $request->phone;
            $shop->shop_type = $request->shop_type;

        DB::beginTransaction();
        try{            
             //save shop details
            $vendor->Shops()->save($shop);
            //throw custom Exception
            throw new \Exception('User not created for account');
        }

        catch (Exception $e){
        //catch exception and rollback
            DB::rollback();
        }


    }
}
型号:
1) 商店:

2) 卖主

显示数据库引擎的MySQL表详细信息

mysql>显示表状态,其中
Name
='shops'; +-------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+|名称|引擎版本|行|格式|行|平均行|长度| 数据长度|最大数据长度|索引长度|数据自由| 自动递增|创建|更新|检查|时间| 排序规则|校验和|创建|选项|注释| +-------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+|商店| InnoDB| 10 |紧凑型| 1 | 16384 |
16384 | 0 | 16384 | 0 | 17 | 2016-07-03 04:56:27 | NULL | NULL | utf8 | u general | u ci |
空| || +-------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+一行一组(0.00秒)

mysql>显示表状态,其中
名称
=“供应商”; +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+|名称|引擎版本|行|格式|行|平均行|长度| 数据长度|最大数据长度|索引长度|数据自由| 自动递增|创建|更新|检查|时间| 排序规则|校验和|创建|选项|注释| +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+|供应商| InnoDB| 10 |紧凑型| 1 | 16384 |
16384 | 0 | 0 | 0 | 6 | 2016-07-07 00:46:08 | NULL | NULL | utf8 | u general | u ci |
空| || +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+一行一组(0.00秒)


请帮助。

您必须使用
DB::commit()用于提交您的查询。仔细阅读手册

您必须使用
DB::commit()用于提交您的查询。仔细阅读手册

我相信问题不在于拉雷维尔的交易,而在于
catch
声明。尝试替换:

try {
   ...
} catch (Exception $ex) {
   ...
}
以下是:

try {
   ...
} catch (\Exception $ex) {
   ...
}

请注意,
Exception
不同于
\Exception

我认为问题不在Laravel的事务中,而在于
catch
语句。尝试替换:

try {
   ...
} catch (Exception $ex) {
   ...
}
以下是:

try {
   ...
} catch (\Exception $ex) {
   ...
}

请注意,
Exception
不同于
\Exception

为什么不直接使用事务

若它不会在供应商内部创建shop,那个么只需处理您的自定义异常即可

如果您试图回滚不成功的执行,则db rollback是一个伪函数

    try{            
        //save shop details
        if(!$vendor->Shops()->save($shop)) {
          //throw custom Exception
          throw new \Exception('User not created for account');
        }
    }
    catch (Exception $e){
        //catch exception and do anything You wanted (without db::rollback)
    }

为什么不干脆不做交易呢

若它不会在供应商内部创建shop,那个么只需处理您的自定义异常即可

如果您试图回滚不成功的执行,则db rollback是一个伪函数

    try{            
        //save shop details
        if(!$vendor->Shops()->save($shop)) {
          //throw custom Exception
          throw new \Exception('User not created for account');
        }
    }
    catch (Exception $e){
        //catch exception and do anything You wanted (without db::rollback)
    }

我发现问题出在我的连接上。我在模型中使用自定义连接,而不是默认连接。在Laravel中使用DB facade时,我认为它使用的是默认连接,即mysql,而不是供应商

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Shop extends Authenticatable
{
    protected $connection = 'vendor';\\custom connection
    protected $fillable = [
        'shop_id','vendor_id','name','address','pincode','phone','shop_type'
    ];

    public function Vendor(){
        return $this->belongsTo('App\Models\Vendor','vendor_id','vendor_id');
    }

    public function Products(){
        return $this->belongsToMany('App\Models\Product')->withPivot('mfg_date', 'exp_date','active','quantity');
    }
}
我的数据库配置文件中的连接:

'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'shop',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => 'InnoDB',
        ],

        'vendor' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'shop',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => 'InnoDB',
        ]
    ],
现在,我的商店管理员以以下方式调用事务

 class shopController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function getView()
    {
        if(Auth::user()->shop_status==0)
            return View::make('shop')->with('name',json_encode(Auth::user()->Vendor_Detail()->get(['first_name', 'last_name'])));
        else
            return redirect('/home');
    }

    public function addShop(ShopDataRequest $request){
    //get the logged in vendor's model instance. Auth uses Vendor model
            $vendor = Auth::user();
    //create new Shop Model
            $shop = new Shop;
            $shop->name = $request['shop_name'];
            $shop->address = $request->addressLine1;
            $shop->pincode = $request->pincode;
            $shop->phone = $request->phone;
            $shop->shop_type = $request->shop_type;

        //getting the required connection
        $connection = DB::connection('vendor');

        $connection::beginTransaction();//calling the beginTransaction() on connection
        try{            
             //save shop details
            $vendor->Shops()->save($shop);
            //throw custom Exception
            throw new \Exception('User not created for account');
        }

        catch (Exception $e){
        //catch exception and rollback
            $connection::rollback(); //calling the rollback() on connection
        }


    }
}

而且它工作得很好。

我发现问题出在我的连接上。我在模型中使用自定义连接,而不是默认连接。在Laravel中使用DB facade时,我认为它使用的是默认连接,即mysql,而不是供应商

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Shop extends Authenticatable
{
    protected $connection = 'vendor';\\custom connection
    protected $fillable = [
        'shop_id','vendor_id','name','address','pincode','phone','shop_type'
    ];

    public function Vendor(){
        return $this->belongsTo('App\Models\Vendor','vendor_id','vendor_id');
    }

    public function Products(){
        return $this->belongsToMany('App\Models\Product')->withPivot('mfg_date', 'exp_date','active','quantity');
    }
}
我的数据库配置文件中的连接:

'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'shop',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => 'InnoDB',
        ],

        'vendor' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'shop',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => 'InnoDB',
        ]
    ],
现在,我的商店管理员以以下方式调用事务

 class shopController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function getView()
    {
        if(Auth::user()->shop_status==0)
            return View::make('shop')->with('name',json_encode(Auth::user()->Vendor_Detail()->get(['first_name', 'last_name'])));
        else
            return redirect('/home');
    }

    public function addShop(ShopDataRequest $request){
    //get the logged in vendor's model instance. Auth uses Vendor model
            $vendor = Auth::user();
    //create new Shop Model
            $shop = new Shop;
            $shop->name = $request['shop_name'];
            $shop->address = $request->addressLine1;
            $shop->pincode = $request->pincode;
            $shop->phone = $request->phone;
            $shop->shop_type = $request->shop_type;

        //getting the required connection
        $connection = DB::connection('vendor');

        $connection::beginTransaction();//calling the beginTransaction() on connection
        try{            
             //save shop details
            $vendor->Shops()->save($shop);
            //throw custom Exception
            throw new \Exception('User not created for account');
        }

        catch (Exception $e){
        //catch exception and rollback
            $connection::rollback(); //calling the rollback() on connection
        }


    }
}

而且它工作得很好。

即使在回滚之后我也需要使用commit()吗?您需要在保存之后使用。throw Exception之前删除throw Exception是否需要添加迁移或架构以使其工作?即使在回滚()之后,我是否需要使用commit?您需要在保存之后使用。throw Exception之前删除throw Exception是否需要添加迁移或模式才能工作?我也尝试过这种方法。但是,它无法工作。事实上,问题在于我的连接。看看我的答案。我也尝试过这种方法。但是,它无法工作。事实上,问题在于我的连接。看看我的答案。嗨,乔基。你能解释一下Exception和\Exception之间的区别吗?如果你的代码是命名空间的,那么PHP将解析clas