在laravel中同时将数据保存到两个表中

时间:2017-10-05 12:00:10

标签: php laravel laravel-5 model eloquent

我试图将数据保存到两个不同的表中取决于选择(x-editable)。这是我的代码,并指出我在做错误的地方帮助我。

我正在寻找的结果:我将TBL中的付款状态更改为已付款:产品,付款值在TBL中也会更改为0:Product_payment

TBL:产品

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

TBL:Product_payment

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

控制器:

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');
    }
}

1 个答案:

答案 0 :(得分:0)

只要保存boot的实例,就会AppServiceProvidera model event listener添加到Product

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]]);
    }
});