Laravel - 雄辩地覆盖自定义时间戳......为什么?

2024-05-07

我正在制作一个库存管理系统。 当产品缺货时,我会在表中输入一个条目,并记下“oos_at”字段和日期/时间。

后来,当它回到库存时,我找到该条目并更新“restocked_at”时间戳字段。

但是,当我执行第二个操作时,我的“oos_at”字段被查询的时间戳(“updated_at”)字段覆盖...... 我必须跟踪另一个实体上的这个“oos_at”字段,这样它就不会被覆盖,然后在更新该表时使用该字段再次更新“oos_at”字段......

下面是我的代码......

class Pusher extends Model {
/**
 *
 *
 * @param Carbon $oos_at
 * @return bool
 */
public function setAsOutOfStock(Carbon $oos_at)
{
    Log::info([
        'FILE'  => get_class($this),
        'method'   => 'setAsOutOfStock',
        'pusher'    => $this->id,
        'param:oos_at'  => $oos_at->toDateTimeString(),
    ]);

    $this->pusherOutOfStocks()->create([
        'location_id'   => $this->location_id,
        'product_id'    => $this->product_id,
        'oos_at'        => $oos_at->toDateTimeString(),
    ]);

    $this->oos = true;
    $this->oos_at = $oos_at;
    return $this->save();
}

/**
 * Clear the PusherOutOfStocks attached to $this Pusher
 * (This Pusher has been restocked!)
 *
 * @param Carbon $time
 * @return bool
 */
public function setAsInStock(Carbon $time)
{
    Log::info([
        'FILE'      => get_class($this),
        'method'    => 'setAsInStock',
        'pusher'    => $this->id,
        'param:time' => $time->toDateTimeString(),
    ]);

    $this->pusherOutOfStocks()->where('restocked_at', null)
        ->update(['restocked_at' => $time->toDateTimeString()]);

    $this->oos = false;
    $this->oos_at = null;
    return $this->save();
}
}

当我死亡并在推杆重新进货之前转储 PusherOutOfStocks 时,“oos_at”会被适当设置。

Illuminate\Database\Eloquent\Collection {#340
  #items: array:1 [
    0 => Newave\Engineering\PusherOutOfStock {#343
      #fillable: array:5 [
        0 => "pusher_id"
        1 => "location_id"
        2 => "product_id"
        3 => "oos_at"
        4 => "restocked_at"
      ]
      #dates: array:2 [
        0 => "oos_at"
        1 => "restocked_at"
      ]
      #connection: null
      #table: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:9 [
        "id" => 246
        "pusher_id" => 216
        "location_id" => 634
        "product_id" => 378
        "oos_at" => "2016-03-11 03:00:00"
        "restocked_at" => null
        "created_at" => "2016-03-11 12:12:01"
        "updated_at" => "2016-03-11 12:12:01"
        "deleted_at" => null
      ]
      #original: array:9 [
        "id" => 246
        "pusher_id" => 216
        "location_id" => 634
        "product_id" => 378
        "oos_at" => "2016-03-11 03:00:00"
        "restocked_at" => null
        "created_at" => "2016-03-11 12:12:01"
        "updated_at" => "2016-03-11 12:12:01"
        "deleted_at" => null
      ]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [
        0 => "*"
      ]
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
      #forceDeleting: false
    }
  ]
}

当我死亡并在推杆重新进货后转储 PusherOutOfStocks 时,“oos_at”与“updated_at”相同

Illuminate\Database\Eloquent\Collection {#408
  #items: array:1 [
    0 => Newave\Engineering\PusherOutOfStock {#775
      #fillable: array:5 [
        0 => "pusher_id"
        1 => "location_id"
        2 => "product_id"
        3 => "oos_at"
        4 => "restocked_at"
      ]
      #dates: array:2 [
        0 => "oos_at"
        1 => "restocked_at"
      ]
      #connection: null
      #table: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:9 [
        "id" => 244
        "pusher_id" => 214
        "location_id" => 626
        "product_id" => 374
        "oos_at" => "2016-03-11 12:10:23"
        "restocked_at" => "2016-03-11 04:00:00"
        "created_at" => "2016-03-11 12:10:22"
        "updated_at" => "2016-03-11 12:10:23"
        "deleted_at" => null
      ]
      #original: array:9 [
        "id" => 244
        "pusher_id" => 214
        "location_id" => 626
        "product_id" => 374
        "oos_at" => "2016-03-11 12:10:23"
        "restocked_at" => "2016-03-11 04:00:00"
        "created_at" => "2016-03-11 12:10:22"
        "updated_at" => "2016-03-11 12:10:23"
        "deleted_at" => null
      ]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [
        0 => "*"
      ]
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
      #forceDeleting: false
    }
  ]
}

我什至使用过 DB::getQueryLog() 并且没有看到“oos_at”被显式设置/更新......

我的代码中的其他地方都没有修改此表...

有谁明白这里发生了什么吗? 谢谢你!!

=============

额外的代码片段

表迁移::

    Schema::create('pusher_out_of_stocks', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('pusher_id');
        $table->integer('location_id');
        $table->integer('product_id');

        $table->timestamp('oos_at');
        $table->timestamp('restocked_at')->nullable();

        $table->timestamps();
        $table->softDeletes();
    });

PusherOutOfStock 类

class PusherOutOfStock extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'pusher_id',
        'location_id',
        'product_id',
        'oos_at',
        'restocked_at',
    ];

    protected $dates = [
        'oos_at',
        'restocked_at'
    ];

    /**
     * A PusherOutOfStock belongsTo a Product
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * A PusherOutOfStock belongsTo a Pusher
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function pusher()
    {
        return $this->belongsTo(Pusher::class);
    }

    /**
     * A PusherOutOfStock belongsTo a Location
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function location()
    {
        return $this->belongsTo(Location::class);
    }
}

下面是代码执行该更新方法所经历的顺序

首先,它会访问我的 API 命名空间中的 InventoryController

    public function upload(Request $request)
    {
        $data = $request->all();

        $header = $this->getHeader($data);
        $body   = $this->getBody($data);

        $reader = $this->getReaderFromHeader($header);

        if ( ! $this->guardAgainstNoReader($reader))
            return (new Response("Reader with mac-address: ". $header['reader_mac'] . " does not exist.", 409));

        $result = $this->inventoryRepository->uploadPusherData($reader, $header, $body);

        return $result;
    }

然后它将请求发送到库存存储库

public function uploadPusherData(Reader $reader, $header, $body)
{
    foreach ($body as $pusherData)
    {
        $result[] = $this->processPusherData($pusher, $header['timestamp'], $pusherData);
    }
    return $result;
}

然后,在存储库内,它一次处理一行(在我的测试中,只有一行)

private function processPusherData(Pusher $pusher, $timestamp, $pusherData)
{
    $latestInventory = $pusher->latestInventory;

    if (! $latestInventory)
        return $this->updatePusher($pusher, $timestamp, $pusherData);

    if ($latestInventory->tags_blocked == $pusherData['data_TAGSBLKED'])
        return $this->noChangeRecorded($pusher, $latestInventory, $timestamp);

    return $this->updatePusher($pusher, $timestamp, $pusherData);
}

然后推送器就更新了...

public function updatePusher($pusher, $timestamp, $pusherData)
{
    // See if there are any existing already
    $prevInv = $pusher->latestInventory;

    // Create the new data
    $inventory = Inventory::create([
        'pusher_id'     => $pusher->id,
        'product_id'    => $pusher->product_id,
        'reader_id'     => $pusher->reader->id,
        'tags_blocked'  => $pusherData['data_TAGSBLKED'],
        'paddle_exposed'=> $pusherData['paddle_exposed'],
        'created_at'    => Carbon::createFromTimestamp($timestamp)
                            ->toDateTimeString(),
    ]);

    if (  !$prevInv || $prevInv->id == $inventory->id )
    {
        return "first-data" . $timestamp;
    }

    return $this->checkForEvents($inventory, $prevInv);
}

我们检查是否应该触发任何事件...在本例中,之前的库存有 9 件库存...现在有 0 件。

private function checkForEvents(Inventory $currentInventory, Inventory $previousInventory)
{
    if ( ! $previousInventory->oos && $currentInventory->oos && $previousInventory->pusher->oos_notified == 0)
    {
        $currentInventory->pusher->oos_notified = true;
        $currentInventory->pusher->save();
        return Event::fire(new InventoryOutOfStock($currentInventory));

    }

    if ( ( $previousInventory->oos || $previousInventory->status == "RESTOCK" )
            && $currentInventory->tags_blocked > 2 )
    {
        return Event::fire(new PusherWasRestocked($currentInventory));
    }

    if ( $currentInventory->status == "RESTOCK" && $previousInventory->pusher->low_stock_notified == 0)
    {
        $currentInventory->pusher->low_stock_notified = true;
        $currentInventory->pusher->save();
        return Event::fire(new LowStockAlert($currentInventory));
    }

    return "no-events";
}

然后触发 InventoryOutOfStock 事件

这会触发 3 个事件...2 个与发送的通知等相关...

    'App\Events\InventoryOutOfStock' => [
        'App\Listeners\InventoryOutOfStockUpdater',
        'App\Listeners\EmailInventoryOutOfStockNotification',
        'App\Listeners\SMSInventoryOutOfStockNotification',

// 'App\Listeners\OutOfStocksUpdater', ],

这导致我们...

public function handle(InventoryOutOfStock $event)
{
    $pusher = $event->pusher;
    $inventory = $event->inventory;
    $product = $pusher->product;

    $oos = $pusher->setAsOutOfStock($inventory->created_at);

    $locationPushers = $product->getPushersByLocation($pusher->location);
    $isInStock = false;
    foreach ($locationPushers as $pusher)
        if ($pusher->oos == 0)
            $isInStock = true;

    if (! $isInStock)
        $product->productOutOfStocks()->create([
            'location_id'   => $pusher->location_id,
            'oos_at'        => $event->inventory->created_at,
        ]);
}

我认为你不必使用timestamp方法来创建您的字段,但您应该使用dateTime method:

Schema::create('pusher_out_of_stocks', function (Blueprint $table) {
    $table->increments('id');

    $table->integer('pusher_id');
    $table->integer('location_id');
    $table->integer('product_id');

    $table->dateTime('oos_at');
    $table->dateTime('restocked_at')->nullable();

    $table->timestamps();
    $table->softDeletes();
});

这应该有效:)

希望有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel - 雄辩地覆盖自定义时间戳......为什么? 的相关文章

  • MySql - 自动完成

    我正在创建一个 Ajax 自动完成应用程序 并且想知道是否有一个 SQL 查询可以用于此目的 例如 如果有人键入 p 我想检索所有以 p 开头的单词 如果他们添加 e 检索所有以 pe 开头的单词 并继续这样 有人提出了下面的查询 但我认为
  • 如何使用 Sequel Pro 在导入过程中将字符串更改为日期?

    我正在尝试使用 Sequel Pro 将文件导入到 MySQL 表中 我知道我需要使用 STR TO DATE 但我无法找出正确的语法 我在每一行都收到一堆这样的错误 ERROR in row 1 You have an error in
  • MYSQL sum() 计算不同的行

    我正在寻求在 SQL 查询中使用 sum 的帮助 SELECT links id count DISTINCT stats id as clicks count DISTINCT conversions id as conversions
  • 如何将html表单中的信息写入MySQL数据库

    好吧 我正在建立一个带有表单的网站 我想将用户在表单中输入的所有信息保存到我的 MySQL 数据库中 表单的编码如下
  • 备份MySQL数据库

    我有一个大约 1 7GB 的 MySQL 数据库 我通常使用 mysqldump 进行备份 这大约需要 2 分钟 但是 我想知道以下问题的答案 mysqldump 是否阻止对数据库的读取和 或写入操作 因为在实际场景中 我不想在备份数据库时
  • 如何根据状态从父表和子表获取数据,其中外键每行具有不同的状态

    我有 2 个具有外键关系的表 情况是我有一个case and a case有很多revisions 和每个revision有自己的status 如果仅更改外键表状态的特定行 我想获取父表数据和子数据 Table Case id case n
  • Rails 创建 schema_migrations - Mysql2::Error: 指定的键太长

    我正在使用Rails 3 2 6和Mysql 6 0 9 但我在MySQL 5 2 25上有完全相同的错误 当我创建新数据库时 rake db create 然后当我尝试加载架构时 rake schema load 我收到此错误 Mysql
  • 通过左连接实现精确分页

    我已经思考这个问题有一段时间了 我认为最好四处询问并听听其他人的想法 我正在构建一个在 Mysql 上存储位置的系统 每个位置都有一个类型 有些位置有多个地址 表格看起来像这样 location location id autoincrem
  • MySQL更改表,添加具有唯一随机值的列

    我有一个表 我添加了一个名为phone 该表还有一个 id 设置为自动增量的主键 如何将随机值插入到电话列中 该值不会重复 以下 UPDATE 语句确实插入了随机值 但并非所有值都是唯一的 另外 我没有被卖掉 我投了phone字段也正确 但
  • REPLACE MYSql 中的新行字符不起作用

    我执行了以下查询 由于某种原因它没有替换数据库中的换行符 它说 Rows matches 1 但没有变化 有什么问题吗 mysql gt UPDATE aboutme SET abouttext REPLACE abouttext n WH
  • 将资源文件链接到 Laravel4 中的视图

    您好 我是新手 正在学习 laravel 4 创建应用程序 我正在尝试使用 laravel Blade 将 twitter bootstrap3 文件链接到视图 我安装了一个新的 laravel 应用程序文件夹 为了从 url 路径中删除
  • 将 php filter_var 与 mysql_real_escape_string 结合使用

    我想首先说 我意识到 PDO mysqli 是新标准 并且已被 SO 广泛覆盖 然而 在这种特殊情况下 我没有时间在启动客户端站点之前将所有查询转换为 PDO 以下内容已在网站上的大多数查询中使用 我可以补充一下 这不是我所使用的 user
  • RESTful Web 服务:java.lang.NullPointerException service.AbstractFacade.findAll

    我使用 NetBeans 7 的 来自数据库的 RESTful Web 服务 向导创建了一个简单的 XML Web 服务 此时 我想从关联的 mySQL 数据库发布用户列表 当我尝试通过其 URL http localhost 8080 d
  • barryvdh/laravel-dompdf:- fopen 无法打开流:laravel 5.7 中没有这样的文件或目录

    当我想下载发票 pdf 时出现错误 fopen project path storage fonts 071ddd89a9cb147bf5639344caee3fe8 ufm 无法打开流 没有这样的文件或目录 在此输入图像描述 https
  • 使用 PHP 将文件上传到 MySql DB

    我希望用户通过我在后端使用 MySql 用 PHP 开发的 web 应用程序上传文件 我想将文件存储在数据库中 我在这样做时遇到了问题 此外 一旦文件存储在数据库中 我们如何下载它 并在 web 应用程序中正确显示它 文件类型和文件的其他属
  • 存储过程函数中的动态表名

    我编写了一个存储过程函数来从表中获取名称 问题是我希望将表名作为参数传入 有几个不同的表我需要使用此函数 DELIMITER CREATE DEFINER root localhost FUNCTION getName tableName
  • 如何通过 MySQL Workbench 或 CLI 或 MySQLWeb 数据库管理应用程序连接到 Pivotal Cloud Foundry (PCF) 上的 MySQL 服务?

    我有一个Spring Boot based REST部署在的应用程序Pivotal Cloud Foundry PCF 并且工作正常 但是这个 REST 应用程序到目前为止还没有任何数据库连接 因此 我决定安装MySQL服务于PCF从市场上
  • https 重定向 laravel .htaccess 之后删除 /public

    我有一个 Laravel 页面部署在共享主机中 当我强制 http 请求重定向到 https 时 url 包含 public 我的根 htaccess 是 RewriteEngine on RewriteCond REQUEST URI p
  • MySQL 查询中的窗口函数

    有没有办法在 SELECT 查询本身中动态地使用 MySQL 查询中的窗口函数 我知道在 PostgreSQL 中这是可能的 例如 下面是 PostgreSQL 中的等效查询 SELECT c server ip c client ip s
  • pyodbc 无法正确处理 unicode 数据

    我确实使用 pyodbc 成功连接了 MySQL 数据库 并且它可以很好地处理 ascii 编码的数据 但是当我打印使用 unicode utf8 编码的数据时 它引发了错误 UnicodeEncodeError ascii codec c

随机推荐