【发布时间】: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(); });