我想得到' loan_id'插入两个表中。
return $this->getConnection()->getPdo()->lastInsertId();
我想我应该至少得到最后一个id(这个模型被指定为' id'并且自动增加)但我也没有收到它。 (只是空洞的回应)
如果我可以获得插入数据库中的完整对象,那就更好了。
所以,我希望在事务失败时捕获异常并在发生故障时返回错误消息,并在成功的情况下返回$ loan_id或保存的Object。怎么做?
<?php
namespace App\model;
use Illuminate\Database\Eloquent\Model as Eloquent;
//use Illuminate\Support\Facades\DB as DB;
use Illuminate\Support\Manager as Manager;
use Illuminate\Database\Capsule\Manager as DB;
use PDO;
class Loan extends Eloquent
{
protected $table = 'loans';
protected $primaryKey = 'id';
public $timestamps = false;
public function addLoan($amount, $instalments)
{
// Manager::connection()->getPdo()->beginTransaction();
$this->getConnection()->transaction(function () use ($amount)
{
$loan_id = substr(uniqid(), -12);
DB::table('loans')->insert([
'loan_id' => $loan_id,
'amount' => $amount,
'status' => 'requested'
]
);
DB::table('loan_instalment')->insert([
'loan_id' => $loan_id,
'principal' => 777.12,
'interest' => 333.12
]
);
});
return $this->getConnection()->getPdo()->lastInsertId();
}
}
?>
答案 0 :(得分:1)
而不是
$this->getConnection()->getPdo()->lastInsertId()
你可以这样做:
DB::table('table')->insert([...])->lastInsertId();