bastinald / laravel-automatic-migrations

Automatic Laravel model migrations.
42 stars 11 forks source link

Relations when it comes to seeds #1

Closed MACscr closed 3 years ago

MACscr commented 3 years ago

One thing i am struggling to figure out how to do relations with the seed data in the definition(). Not sure how i can make that 'contact_id' in the seed related to an actual contact from the Contact model. Will be useful to know for other uses. Right now i just have a hard contact id set of 1.

<?php

namespace App\Models;

use Bastinald\UI\Traits\HasFillable;
use Faker\Generator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;

class Transaction extends Model
{
    use HasFactory;
    use HasFillable;
    use SoftDeletes;

    public function migration(Blueprint $table)
    {
        $table->id();
        $table->unsignedBigInteger('contact_id');
        $table->string('description');
        $table->string('payment_gateway');
        $table->string('gateway_transaction_id');
        // create unique relationship
        $table->unique(['payment_gateway', 'gateway_transaction_id']);
        $table->decimal('amount', 10, 2);
        $table->decimal('fees', 10, 2)->default(0.00);
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
        $table->softDeletes();
    }

    public function definition(Generator $faker)
    {
        return [
            'contact_id' => 1,
            'description' => $faker->words,
            'payment_gateway' => 'square',
            'gateway_transaction_id' => $faker->unique()->numerify('########'),
            'amount' => $faker->randomFloat(2, 10, 20),
            'fees' => $faker->randomFloat(2, 0, 0.4),
        ];
    }
}
bastinald commented 3 years ago

The way I normally do it is I would seed contacts BEFORE transactions, then in my transaction seeder do something like this:

public function definition(Generator $faker)
{
    return [
        'contact_id' => Contact::inRandomOrder()->first()->id,
        'description' => $faker->words,
        'payment_gateway' => 'square',
        'gateway_transaction_id' => $faker->unique()->numerify('########'),
        'amount' => $faker->randomFloat(2, 10, 20),
        'fees' => $faker->randomFloat(2, 0, 0.4),
    ];
}
MACscr commented 3 years ago

Perfect! Thanks!