Laravel 作业批处理表与用户模型的关系?

如何解决Laravel 作业批处理表与用户模型的关系?

我正在使用 Laravel Job Batching 功能,并且我有仪表板,我可以在其中显示 Batch 的进度(已处理、失败、待处理作业等)。

每个用户都有自己的仪表板,我想根据登录用户显示批处理的进度,但是我看不到与批处理表 job_batches 的用户模型有任何关系。

是否有可能以某种方式与这些表建立关系?或任何其他选择?

谢谢

解决方法

只有我在本地执行作业时修改它:

$this->connection->table($this->table)
        ->where('id',$batch->id)->update([
            'user_id' => Auth::user()->id ?? null,]);
,

这是可能的,但还有很多困难要经过。这也可能是关于扩展 Laravel 功能的一般方法的问题。

一些简单的假设是您在创建批次时使用了某种身份验证,因此您可以执行 Auth::user()->id

通过迁移为 user_id 表创建您的 job_batches

    Schema::table('job_batches',function (Blueprint $table) {
        $table->unsignedBigInteger('user_id')->after('name')->nullable();
        $table->foreign('user_id')->references('id')->on('users');
    });

Laravel 使用 BatchRepositoryjob_batches 表中创建批次,扩展它并添加我们的逻辑以将用户插入到行中。我已将自定义存储库添加到 App\Repositories 命名空间。一般使用当前逻辑,在核心Laravel逻辑执行后更新user_id。

<?php

namespace App\Repostories;

use Illuminate\Bus\DatabaseBatchRepository;
use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Facades\Auth;

class BatchRepository extends DatabaseBatchRepository
{
    public function store(PendingBatch $batch)
    {
        $batch = parent::store($batch); // TODO: Change the autogenerated stub

        $this->connection->table($this->table)
            ->where('id',$batch->id)->update([
                'user_id' => Auth::user()->id,]);

        return $batch;
    }
}

要使 Laravel 使用您的新类,您需要扩展 Container 中的当前类。第三个参数是表名,假设您使用的是默认表。这是在提供程序中完成的。要么把它放在现有的提供者中,要么创建一个新的,记得注册。

use Illuminate\Bus\BatchFactory;
use Illuminate\Bus\BatchRepository;
use Illuminate\Database\Connection;
use App\Repostories\BatchRepository as CustomBatchRepository;

...

public function register()
{
    $this->app->extend(BatchRepository::class,function () {
        return new CustomBatchRepository(resolve(BatchFactory::class),resolve(Connection::class),'job_batches');
    });
}

使用以下代码段进行测试,这会将 user_id 添加到表行中。

Bus::batch([new TestJob(),new TestJob()])->dispatch();

关系

BatchRepositories 返回一个不是 Eloquent 模型的 Batch。因此,我建议为关系目的创建您自己的 Eloquent 模型,并在您想要手头的批处理功能时制作逻辑将其转换为 Batchfinished()

首先是您的 Batch.php 的 Eloquent 模型。同时还准备了 toBatch() 功能,将 Eloquent 模型转换为 Batch 类。

namespace App;

use Illuminate\Bus\BatchRepository;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Batch extends Model
{
    use HasFactory;

    protected $table = 'job_batches';

    public function toBatch()
    {
        return resolve(BatchRepository::class)->toBatch($this);
    }
}

在您的 User.php 上创建您的关系方法。

public function batches()
{
    return $this->hasMany(Batch::class);
}

我使用以下代码段测试了关系设置,效果很好。

User::first()->batches->first()->toBatch();

其次想象有多个批次,您将能够轻松获得具有更高阶函数的 Batch 类。或者将它们用作适当的关系。

User::first()->batches->map->toBatch();

注意

小心导入正确的 BatchBatchRepository 类。我添加了导入以确保您包含正确的导入,以及提供程序的以下片段,使您能够实例化我的自定义批处理存储库。

use App\Repostories\BatchRepository as CustomBatchRepository;

$this->app->bind(CustomBatchRepository::class,function () {
    return new CustomBatchRepository(resolve(BatchFactory::class),'job_batches');
});

您可以自行承担风险,在为此问题创建的粗略测试场中看到 my solution。有一个控制器和用户的关系。不确定其他 StackoverFlow 项目是否有剩余。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res