2017-10-05 54 views
0

我試圖將數據保存到兩個不同的表中,取決於選擇(x-editable)。這裏是我的代碼,通過指出我犯的錯誤來幫助我。在laravel中同時將數據保存到兩個表中

結果,我在尋找:我改變付款狀態掛起,以支付TBL:產品,支付值也TBL更改0到1:Product_payment

TBL:產品

- product_id 
- client_id 
... 
- status {paid/pending} 

TBL:Product_payment

- product_id 
- payment_id 
.... 
- paid {1/0} 

控制LER:

public function update() 
{ 

    $inputs = Input::all(); 
     if ($row = Product::with('payments')->find($inputs['pk'])) 
     { 
      $row->$inputs['name'] = $inputs['value']; 
      if($row['status'] == 'paid') { 
       $row['paid'] = 1; 
      } 
      $row->save(); 
      return $row; 

} 

Product.php(模型)

class Product extends Eloquent 
{ 
    protected $primaryKey = 'product_id'; 
    protected $table = 'products'; 

    protected $fillable = array('client_id', 'date', 'amount', 'status', 'notes'); 

    public function payments() 
    { 
     return $this->hasMany('ProductPayment'); 
    } 

} 

ProductPayment.php(模型)

class ProductPayment extends Eloquent 
{ 
    public $table = 'product_payments'; 
    protected $primaryKey = 'product_payment_id'; 


    protected $fillable = array('product_id', 'client_id', 'payment_method', 'amount_paid', 'paid'); 

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

    public function clients() 
    { 
     return $this->belongsTo('Clients'); 
    } 
} 
+0

任何人,請讓我知道如果我的問題不清楚回答。 – mkrahamath

回答

0

AppServiceProvider添加a model event listenerboot每當一個的實例保存。

Product::saved(function ($product) { 
    $paymentStatus = [ 
     'pending' => 0, 
     'paid' => 1, 
    ]; 

    if(array_key_exists($product->status, $paymentStatus)) 
    { 
     ProductPayment::where('product_id', $product->id) 
      ->update(['paid' => $paymentStatus[$product->status]]); 
    } 
}); 
+0

謝謝你的代碼,它的工作原理 – mkrahamath

相關問題