首页 > 后端开发 > php教程 > 用Laravel的回收方法优化工厂数据创建

用Laravel的回收方法优化工厂数据创建

百草
发布: 2025-03-06 02:08:09
原创
844 人浏览过

Optimizing Factory Data Creation with Laravel's recycle Method

Laravel的工厂系统提供了有效数据创建的强大方法。当构建具有互连关系的复杂数据结构,避免冗余模型实例化时,此方法特别有用。 该方法重复了多个工厂呼叫的现有模型实例,从而大大提高了性能。

让我们用电子商务方案进行说明:> recycle recycle此示例演示了如何简化测试数据库的创建。 与其反复创建

实例,
<?php namespace Tests;

use App\Models\Store;
use App\Models\Product;
use App\Models\Category;
use App\Models\Order;
use Tests\TestCase;

class StoreTest extends TestCase
{
    public function test_sales_report_generation()
    {
        // Establish foundational data
        $store = Store::factory()->create();
        $categories = Category::factory(3)->recycle($store)->create();

        // Populate categories with products
        $products = Product::factory(20)->recycle($store)->recycle($categories)->create();

        // Generate orders referencing existing products
        $orders = Order::factory(50)->recycle($store)->recycle($products)->create()->each(function ($order) use ($products) {
            // Assign random products to each order
            $orderProducts = $products->random(rand(1, 5));
            $order->products()->attach(
                $orderProducts->pluck('id')->mapWithKeys(function ($id) {
                    return [$id => ['quantity' => rand(1, 5)]];
                })
            );
        });

        // Validate report generation
        $report = $store->generateSalesReport();
        $this->assertNotNull($report);
        $this->assertEquals(50, $report->total_orders);
    }
}
登录后复制
>方法会重复使用它们,从而导致更快的测试执行和减少的资源消耗。 在处理应用程序模型中的大型数据集或复杂关系时,这尤其有益。

以上是用Laravel的回收方法优化工厂数据创建的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板