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

2

I do not know how I do with my Seeds, I have 2 entities: Category and Subcategory. I want to be able to run seeds and be able to register my Categories and after my Subcategories, only Subcategory has a relationship with Category: needs id of Category for insert .

In addition to insert it also has the question of delete if you give a RESET to seeds :

relacionamento 1 > N
    
asked by anonymous 16.03.2014 / 18:01

2 answers

2

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

Regarding migration reset, you can instruct your Database not to perform foreign key checks. In MySQL it 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;');
}
    
16.03.2014 / 18:39
1

And why not just create one 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);

It's simpler!

    
26.03.2014 / 22:15