php - 我无法在 Laravel 中使用事务

标签 php mysql laravel laravel-5

我正在使用 Laravel 开发一个业余爱好项目(商店管理)。我正在尝试使用 DB::beginTransaction() 和 DB::rollback(),但它不起作用。根据我的代码,我认为数据库中不应填充任何条目。

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

这是我的 Shop Controller 文件。

    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)商店:

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Shop extends Authenticatable
{
    protected $connection = 'vendor';
    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');
    }
}

2) 供应商

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Vendor extends Authenticatable
{
    protected $connection = 'vendor';
    protected $primaryKey = 'vendor_id';
    protected $fillable = [
        'email','phone','password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

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

    public function Shops(){
        return $this->hasMany('App\Models\Shop','vendor_id','vendor_id');
    }
    public function Documents(){
        return $this->hasMany('App\Models\Vendor_document','vendor_id','vendor_id');
    }
}

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

mysql> SHOW TABLE STATUS WHERE Name = 'shops'; +-------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +-------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+ | shops | InnoDB | 10 | Compact | 1 | 16384 |
16384 | 0 | 16384 | 0 | 17 | 2016-07-03 04:56:27 | NULL | NULL | utf8_general_ci |
NULL | | | +-------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+ 1 row in set (0.00 sec)

mysql> SHOW TABLE STATUS WHERE Name = 'vendors'; +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+ | vendors | InnoDB | 10 | Compact | 1 | 16384 |
16384 | 0 | 0 | 0 | 6 | 2016-07-07 00:46:08 | NULL | NULL | utf8_general_ci |
NULL | | | +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+-----------------+----------+----------------+---------+ 1 row in set (0.00 sec)

请帮忙。

最佳答案

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

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',
        ]
    ],

现在,我的商店 Controller 按以下方式调用交易。

 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
        }


    }
}

并且它完美地工作。

关于php - 我无法在 Laravel 中使用事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38286855/

相关文章:

PHP 和计划任务

php - 如何使用uniqueid()填充MySQL表中所有记录的字段?

laravel - 数据库[]未配置Laravel 5

php - 如何将数组传递给 laravel 中的 where 子句?

php - 如何在 blade.php 中使用 vue 获取字段的旧值

php - 你如何在 PHP 中获取 'referer' header ?

javascript - 检索当前日期之后的项目

php - 如何处理 Twig 中数组中的缺失值

php - MySQL多表连接

mysql - Rails 连接两个表或用单词替换数字