简体   繁体   English

在laravel中某些情况下自动将数据插入数据库

[英]Automatically insert a data to database in certain cases in laravel

I am new to laravel.我是laravel的新手。 I want to know is there any particular better option to use in the following case in laravel.我想知道在 laravel 的以下情况下是否有更好的选择。 For an example I have a table called product and another table called productlog.例如,我有一个名为 product 的表和另一个名为 productlog 的表。 While a product is created / updated / deleted in those cases I have to insert a log in productlog table.在这些情况下创建/更新/删除产品时,我必须在 productlog 表中插入日志。 I know, I can insert these data directly in the controller while these actions happening.我知道,当这些操作发生时,我可以直接将这些数据插入到控制器中。 Except this laravel has any better feature to use in this case?除了这个 Laravel 在这种情况下有什么更好的功能可以使用?

You want to perform some action while your Eloquent model is processing.您想在 Eloquent 模型正在处理时执行一些操作。 Laravel's Eloquent provide a convenient way to add your own action while the model is completing or has completed some action. Laravel 的 Eloquent 提供了一种方便的方法,可以在模型完成或已完成某些操作时添加您自己的操作。

This is the list of all of the events, eloquent model fired that we can hook into:这是所有事件的列表,我们可以连接到的 eloquent 模型:

  • retrieved : after a record has been retrieved.检索:在检索到记录之后。
  • creating : before a record has been created.正在创建:在创建记录之前。
  • created : after a record has been created. created :在创建记录之后。
  • updating : before a record is updated.更新:在更新记录之前。
  • updated : after a record has been updated.更新:记录更新后。
  • saving : before a record is saved (either created or updated).保存:在保存记录(创建或更新)之前。
  • saved : after a record has been saved (either created or updated).已保存:在保存(创建或更新)记录之后。
  • deleting : before a record is deleted or soft-deleted.删除:在删除或软删除记录之前。
  • deleted : after a record has been deleted or soft-deleted.删除:在记录被删除或软删除之后。
  • restoring : before a soft-deleted record is going to be restored.恢复:在恢复软删除的记录之前。
  • restored : after a soft-deleted record has been restored.恢复恢复软删除的记录后。

For more details check the Laravel documentation here.有关更多详细信息,请在此处查看 Laravel 文档。 Observers/ Model Events观察者/模型事件

I added this in my我在我的

app\\Providers\\AppServiceProvider.php app\\Providers\\AppServiceProvider.php

Product::created(function ($model) {
    $producthistory = new Producthistory();
    $producthistory >product_id = $model->id;
    $producthistory >action = ' Product Created';
    $producthistory >log = "Product created bla bla bla";
    $producthistory >action_by = Auth::id();
    $producthistory >save();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM