vendredi 6 janvier 2017

Laravel factory specifying column twice

I'm using factories for unit testing and so far I haven't had any problems until now:

// This is the factory definition (note: other fields removed for brevity).
// Primary key is not included just like Laravel's docs show.
$factory->define(Media::class, function (Faker\Generator $faker) {
    return [
        'id_media' => $faker->unique()->randomNumber(6),
        'type' => $faker->randomNumber(1)
        // other irrelevant fields
    ];
});


 // This is how I call it on my unit test
 $count = 5;
 $id = 3;
 factory(Media::class, $count)->create([
      'id_media' => $id
 ]);

The problem is that this generates invalid SQL (id_media is there twice):

INSERT INTO media (id_media, type, id_media) VALUES (73052, 2)

If I don't override the id_media property when I call it in my unit test, then the query is valid but it's not what I need. Two things that strike me as odd are:

  • I'm using this all over my tests but the only time invalid SQL is generated is with this factory. I've got around two dozen factories in my app and this is the only problematic one. This particular table has one primary key and no other indexes. The table is as vanilla as they come.
  • This is actually recommended in the Laravel docs. I'm not doing anything out of the ordinary.


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire