【问题标题】:Save data into two tables at same time in laravel在laravel中同时将数据保存到两个表中
【发布时间】:2017-10-05 12:00:09
【问题描述】:

我正在尝试将数据保存到两个不同的表中,具体取决于选择(x 可编辑)。这是我的代码,并通过指出我做错的地方来帮助我。

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

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

【问题讨论】:

  • 如果我的问题不清楚,请告诉我。

标签: php laravel laravel-5 model eloquent


【解决方案1】:

在AppServiceProvider 中将a model event listener 添加到boot 以用于保存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]]);
    }
});

【讨论】:

  • 谢谢@Oluwafemi Sule,您的回答非常有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2020-08-25
  • 1970-01-01
  • 2013-10-05
  • 2014-10-27
相关资源
最近更新 更多