运行laravel可以说明laravel之外的数据库事务

时间:2015-03-13 09:57:34

标签: php laravel

require dirname(dirname(__DIR__)) . '/vendor/autoload.php';
require dirname(__DIR__) . '/config.php';

use Illuminate\Database\Capsule\Manager as DB;

$dbc = new DB;

$dbc->addConnection(array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => DB_NAME,
    'username'  => DB_USER,
    'password'  => DB_PASSWORD,
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => ''
));

$dbc->setAsGlobal();
$dbc->bootEloquent();

$ dbc->的BeginTransaction();

给我这个错误,

PHP Fatal error:  Call to undefined method Illuminate\\Database\\Capsule\\Manager::beginTransaction()

任何人都可以向我提供一些关于如何在laravel之外使用胶囊和数据库事务的帮助。我找不到任何暗示这不起作用的东西?

1 个答案:

答案 0 :(得分:5)

您需要获取连接实例以使用任何与数据库相关的方法(包括beginTransaction)。实现它们的类是Illuminate\Database\Connection。这意味着您需要从管理器获取连接实例并使用它:

use Illuminate\Database\Capsule\Manager as DB;

$capsule = new DB;

$capsule->addConnection(array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => DB_NAME,
    'username'  => DB_USER,
    'password'  => DB_PASSWORD,
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => ''
));

$capsule->setAsGlobal();
$capsule->bootEloquent();

$connection = $capsule->getConnection();
$connection->beginTransaction();