$transaction = Yii::app()->db->beginTransaction();
try {
$transaction=$connection->beginTransaction();
$model = new UserRole();
$model->role_name="new";
$model->save();
$transaction->commit();
Yii::log('Done', 'trace', 'stripe');
}
catch (Exception $e) {
$transaction->rollback();
}
为什么在yii中的begintransaction之后将数据插入到db中,什么是$ connection?我不确切地知道$ connection是什么意思。 在我的config.php我的Db连接如下。
'db' => require(dirname(__FILE__) . '/database.php'),
$connection = array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
);
我的数据库连接在另一个文件database.php
中我得到了错误,
Call to a member function beginTransaction() on a non-object.
为什么在beginTransaction之后没有插入数据?
答案 0 :(得分:1)
<强> 1 即可。在配置文件中设置正确的数据库连接参数:
'db' => array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
)
或在database.php中写入连接数据并将其包含在主配置中:
database.php 中的
return array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
);
main.php (或其他配置文件)中的
'db' => require(dirname(__FILE__) . '/database.php'),
<强> 2 即可。在使用之前定义$connection
变量:
$connection = Yii::app()->db;
try {
$transaction = $connection->beginTransaction();
$model = new UserRole();
$model->role_name = "new";
$model->save();
$transaction->commit();
Yii::log('Done', 'trace', 'stripe');
} catch (Exception $e) {
if (isset($transaction)) {
$transaction->rollback();
}
Yii::log('Error', 'trace', 'stripe');
}