使用sync laravel获取最后一个插入ID

时间:2015-03-10 07:57:26

标签: laravel

我想使用sync获取最后一个插入ID,这是我的代码

$id = $dealer->products()->sync($products);
$dealer_product->payment()->attach($id, $payment_data);

这是我的DealerProduct模型

class DealerProduct extends Eloquent {
    use SoftDeletingTrait;
    protected $guarded = array();

    public function dealer() {
        return $this->hasMany('Dealer');
    }

    public function product() {
        return $this->belongsTo('Product');
    }

    public function items() {
        return $this->belongsToMany('Item', 'dealer_products_has_items');
    }

    public function payment() {
        return $this->belongsToMany('DealerProduct','dealer_product_payments','dealer_product_id');
    }
}

这是我的dealer_product_payments表结构

id  int(10) 
dealer_product_id   int(10)
paid_at date
expires_at  date
note    text

请帮助我,谢谢

1 个答案:

答案 0 :(得分:0)

// Helper functions for inserting characters. static boolean is2468 (char ch) { return (ch == '2' || ch == '4' || ch == '6' || ch == '8'); } static boolean is13579 (char ch) { return (ch == '1' || ch == '3' || ch == '5' || ch == '7' || ch == '9'); } static String morph(String str) { // Use efficient string builder for creating morphed string. StringBuilder newStr = new StringBuilder(); // Last/current character, starting with '0' simplifies // start condition. char lastCh, ch = '0'; // Process every character in string. for (int idx = 0; idx < str.length(); idx++) { // Transfer previous current to last, get current. lastCh = ch; ch = str.charAt(idx); // Put '-' between two odds, '*' between two non-zero evens. if (is13579(lastCh) && is13579(ch)) newStr.append('-'); else if (is2468(lastCh) && is2468(ch)) newStr.append('*'); // Put character there regardless. newStr.append(ch); } // Return string version of string builder. return newStr.toString(); } 将返回一系列像这样的ID

BelongsToMany::sync()

因此,从该数组中,您知道哪些ID已附加