2016-08-09 2 views
1

두 테이블 모두에 삽입 된 'loan_id'를 가져 오려고합니다.Eloquent lastInsertId

return $this->getConnection()->getPdo()->lastInsertId(); 나는 적어도 id (이 모델에 대해 'id'및 autoincremented로 지정해야 함)를 가져야한다고 생각하지만 역시 수신하지 않습니다. (그냥 빈 응답)

내가 DB에 삽입 된 전체 개체를 얻을 수 있다면 더 나아.

그래서 트랜잭션이 실패 할 경우 Exception을 catch하고 실패한 경우 오류 메시지를 반환하고 성공한 경우 $ loan_id 또는 저장된 Object를 반환하려고합니다. 그것을하는 방법?

DB::table('table')->insert([...])->lastInsertId(); 

을 그리고 예외 잡기 참조 :

<?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

두 삽입이있다. last_insert()는 오직 수행 된 마지막 인서트로부터 오직 하나의 id만을 반환하기 때문에 'loan_instalment'로부터 ID를 얻을 수있을 것이다. –

+0

예, 이해합니다. 그러나 나는 어떤 ID도 얻지 못한다. –

답변