Problem with Seed Relationship between Category and Sub-Category in Laravel 4

Asked

Viewed 317 times

2

I don’t know how I do with my Seeds, I have 2 entities: Category and Sub-category. I want to be able to rotate Seeds and be able to register my Categories and after my Sub-categories, only that Sub-category has a relationship with Category: needs the id from Category to the insert.

Beyond the insert also has the issue of delete if a RESET in Seeds:

relacionamento 1 > N

2 answers

2

Manually enter your primary key into your categories so you can create the subcategory relationship.

Regarding the Migration reset, you can instruct your Database not to perform foreign key checking. Mysql would look like this:

public function run()
{
    // Desabilita a checagem de chaves
    DB::statement('SET FOREIGN_KEY_CHECKS = 0;');
    DB::table('categorias')->delete();

    // Suas migrações
    User::create(array(
         'id' => 1,
         'categoria' => 'teste1'
    ));      

    // Habilita novamente checagem de chaves *Importante*   
    DB::statement('SET FOREIGN_KEY_CHECKS = 1;');
}

1

And why not just create an entity?

Migration:

    Schema::create('categories', function($table)
    {

        $table->increments('id');

        $table->integer('parent_id')->nullable();

        $table->string('name');

        $table->boolean('inactive')->default(0);

        $table->timestamps();

        $table->engine = 'InnoDB';

    });

Relationships:

/**
 * Define an inverse one-to-one or many relationship.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function parent()
{
    return $this->belongsTo('Category', 'parent_id');
}

/**
 * Define a one-to-many relationship.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function children()
{
    return $this->hasMany('Category', 'parent_id');
}

To create and assign:

    $parent = new Category;
    $parent->name = 'Parent';
    $parent->save();

    $child = new Category(['name' = 'Child']);

    $parent->children()->save($child);

Makes it simpler!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.