Laravel(5.6)如何使用与其他表的关系来表示表

时间:2018-03-11 11:00:55

标签: php laravel

目前有一些停机时间,并认为我会玩laravel,因为我通常只是将它用于基本的web开发。

我尝试过播种机,并且喜欢将测试数据放入表格的速度更快,但我不确定如何为多个具有关系的表格执行此操作。

在我的情况下,假设我有3个表,一个客户表,一个客户地址表和一个客户购买表。

为客户表播种很容易,因为它是主表,但其他两个表有一个名为customer_id的列,它是返回客户表的引用。

如果我想使用播种机如何编写代码以生成X数量的客户,然后在其他表中创建以下记录,这些记录链接创建的客户。

如果我遗漏了文档中的内容,请道歉。

3 个答案:

答案 0 :(得分:3)

首先,您需要在Customer模型上设置relationship。我假设Customer模型与CustomerAddressCustomerPurchase模型有one-to-many的关系。

<?php

// app/Customer.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public function addresses()
    {
        return $this->hasMany(CustomerAddress::class);
    }

    public function purchases()
    {
        return $this->hasMany(CustomerPurchase::class);
    }
}

接下来,您需要定义model factory

<?php

// database/factories/CustomerFactory.php
use Faker\Generator as Faker;

$factory->define(App\Customer::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
    ];
});

$factory->define(App\CustomerAddress::class, function (Faker $faker) {
    return [
        'address' => $faker->streetAddress,
    ];
});

$factory->define(App\CustomerPurchase::class, function (Faker $faker) {
    return [
        'item' => $faker->word,
        'amount' => $faker->randomFloat(2, 10, 200),
    ];
});

现在,您所要做的就是使用这些模型工厂在数据库上播种随机记录。你仍然可以使用Eloquent集合和relationship就好了:

<?php

// database/seed/DatabaseSeeder.php
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Customer::class, 10)->create()->each(function ($customer) {
            $customerAddresses = factory(App\CustomerAddress::class, 2)->make();
            $customerPurchases = factory(App\CustomerPurchase::class, 5)->make();

            $customer->addresses()->saveMany($customerAddresses);
            $customer->purchases()->saveMany($customerPurchases);
        });
    }
}

希望这会给你一些想法。

答案 1 :(得分:0)

您可以简单地制作foreach声明

$customers = factory(Customer::class,N)->create();
foreach( $customers as $customer)
{
     factory(CustomerAddress::class)->create([
          'customer_id' => $customer->id
     ]);

     factory(CustomerPurchase::class)->create([
          'customer_id' => $customer->id
     ]);
}

注意建议仅在您希望为每位客户提供地址和购买时使用。 否则,您应该区别对待播种,不要为每个客户提供地址和购买 这将使您的测试不太可靠

答案 2 :(得分:0)

文档中的一些修改代码:

$users = factory(Customer::class, 3)
       ->create()
       ->each(function ($u) {
            $u->addresses()->save(factory(Address::class)->make());
            $u->purchases()->saveMany(factory(Purchase::class, 10)->make());
        });