You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10数据库填充时如何确保表中数据唯一?

Laravel 10线索管理系统:解决Statuses表重复填充及API开发要点

一、彻底解决Statuses表重复填充问题

1. 数据库层面加唯一约束(必做)

先确保Statuses表的状态名称字段(比如name)已添加唯一索引,从根源阻止重复数据写入:

// database/migrations/xxxx_xx_xx_create_statuses_table.php
public function up()
{
    Schema::create('statuses', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique(); // 添加唯一约束
        $table->timestamps();
    });
}

如果表已创建,生成新迁移文件补加唯一索引:

php artisan make:migration add_unique_index_to_statuses_name

在新迁移文件中写入:

public function up()
{
    Schema::table('statuses', function (Blueprint $table) {
        $table->unique('name');
    });
}

执行迁移:php artisan migrate

2. 优化数据填充逻辑

放弃手动循环判断,直接用Laravel的firstOrCreate方法自动检测数据是否存在,不存在才创建:

// database/seeders/StatusSeeder.php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Status;

class StatusSeeder extends Seeder
{
    public function run()
    {
        $statuses = [
            'Cancelled',
            'Pending',
            'Followup started',
            'Completed'
        ];

        foreach ($statuses as $statusName) {
            Status::firstOrCreate(
                ['name' => $statusName], // 查询条件
                ['name' => $statusName]  // 待创建字段(可添加其他字段)
            );
        }
    }
}

也可以用集合批量处理:

collect($statuses)->each(function ($name) {
    Status::firstOrCreate(['name' => $name]);
});

执行填充:php artisan db:seed --class=StatusSeeder

3. 清理已存在的重复数据

如果表中已有重复数据,可临时在Seeder中添加以下代码清理(执行一次后删除):

Status::select('name')
    ->groupBy('name')
    ->havingRaw('COUNT(*) > 1')
    ->get()
    ->each(function ($duplicate) {
        // 保留第一条,删除其余重复项
        Status::where('name', $duplicate->name)
            ->skip(1)
            ->delete();
    });

二、线索管理系统API开发要点

1. 快速生成资源控制器

用Laravel命令一键生成带CRUD逻辑的API控制器:

php artisan make:controller Api/StatusController --model=Status --resource
php artisan make:controller Api/LeadController --model=Lead --resource
# 同理生成其他表的控制器

生成的控制器会包含index、store、show、update、destroy等标准API方法。

2. 定义模型关联

根据表结构配置模型关联,比如Lead模型关联Status:

// app/Models/Lead.php
public function status()
{
    return $this->belongsTo(Status::class);
}

IndividualLead、BusinessLead若与Lead存在关联,也要同步定义对应关系。

3. 配置请求验证

为API请求添加验证规则,确保数据有效性,比如创建状态的验证:

// app/Http/Requests/StoreStatusRequest.php
public function rules()
{
    return [
        'name' => 'required|string|unique:statuses,name'
    ];
}

在控制器的store方法中使用该验证:

public function store(StoreStatusRequest $request)
{
    $status = Status::create($request->validated());
    return response()->json($status, 201);
}

4. 统一API返回格式(可选)

用API资源规范返回数据结构:

php artisan make:resource StatusResource

在控制器中调用资源:

use App\Http\Resources\StatusResource;

public function index()
{
    return StatusResource::collection(Status::all());
}

5. 遵循RESTful状态码规范

返回符合标准的HTTP状态码:

  • 200:查询成功
  • 201:创建成功
  • 400:请求参数错误
  • 404:资源不存在
  • 422:验证失败
  • 500:服务器错误

内容的提问来源于stack exchange,提问作者Shemeera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:16:20