【问题标题】:Save data in 2 different tables with laravel使用 laravel 将数据保存在 2 个不同的表中
【发布时间】:2020-08-25 15:42:03
【问题描述】:

如何将记录保存在 2 个不同的表中。 我以这种方式拥有我的文章模型和文章控制器。我的第二张桌子叫做历史 希望大家能帮帮我,非常感谢

我的文章模型:

 protected $fillable =[
        'idcategoria','codigo','nombre','precio_proveedor','precio_venta','iva','ieps','stock','stock1','descripcion','condicion'
    ];
    public function categoria(){
        return $this->belongsTo('App\Categoria');
    }

我的文章控制器,存储方法:

 protected static function boot()
{
    parent::boot();
    // this triggers everytime an Article model is saved
    static::saved(dd($articulo) { dd($article);
        $historial = new Historial();
        $historial->nombre = $articulo->nombre;
        $historial->precio_proveedor = $articulo->precio_proveedor;
        $historial->stock = $articulo->stock;
        $historial->save();
    });
}

在我的历史表中我只需要保存 nombre, precio_proveedor, 库存

【问题讨论】:

  • 每次保存文章模型都需要往History表中放数据吗?
  • 是的,完全正确。我需要复制记录,但只有 nombre、precio_proveedor 和 stock
  • 您可以为此使用观察者。每当保存文章时,您都会更新或创建历史模型。我会发布答案
  • 准备好然后模型好吗?
  • dd($articulo) 喜欢这个static::saved(function (Article $article) { dd($article); $history = new History(); $history->nombre = $article->nombre; $history->precio_proveedor = $article->precio_proveedor; $history->stock = $article->stock; $history->save(); });

标签: mysql laravel vue.js


【解决方案1】:

您可以为此使用观察者。将此添加到您的 Article 模型中:

protected static function boot()
    {
        parent::boot();
        // this triggers everytime an Article model is saved
        static::saved(function (Article $article) {
            $history = new History();
            $history->nombre = $article->nombre;
            $history->precio_proveedor = $article->precio_proveedor;
            $history->stock = $article->stock;
            $history->save();
        });
    }

参考:https://www.larashout.com/how-to-use-laravel-model-observers

【讨论】:

  • 什么也救不了我:(
  • 在您的问题中添加文章模型,以便我检查
  • 删除答案并编辑您的原始问题并将其放在那里。还有dd($articulo) static::saved() 检查你是否得到模型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 2013-12-19
  • 2016-08-13
  • 1970-01-01
相关资源
最近更新 更多