title: Laravel Model factories, one to many relationship without database access
body: <p>For my tests (Laravel 6) I am trying to use factories with <code>make()</code>, in order to <strong>bypass the DB operations</strong> just creating a new instance of the model.</p>
  <p>Now, I am having an headache to make things work with my one to many relationship.</p>
  <p>A skeleton of my code just to have an overview:</p>
  <pre class="lang-php prettyprint-override"><code>class Fine extends Model {
      // Other things here
  
      public function articles()
      {
          return $this-&gt;hasMany('App\Model\Article');
      }
  }
  </code></pre>
  <p>where <code>Article</code> does not have any other relationships.</p>
  <p>Now, I would like to create a Fine factory to create an instance in which I can parse <code>$fine-&gt;articles</code>, all without any database interaction.</p>
  <p>Here's the basic Fine factory that works (without using articles):</p>
  <pre>$factory-&gt;define(Fine::class, function (Faker $faker) {
      return [
          &quot;id&quot; =&gt; 10,
          Fine::FIELDONE =&gt; 'xxx',
          Fine::FIELDTWO =&gt; 'yyy',
      ];
  });
  </pre>
  <p>that I use with <code> $fine = factory(Fine::class)-&gt;make(); </code>.</p>
  <p>Now I need to &quot;prefill&quot; articles. I have tried with <code> hydrate()</code> but it does not work.
  I have tried with <code>afterMaking()</code> with different combinations of code:</p>
  <pre><code>$factory-&gt;afterMaking(Fine::class, function (Fine $fine, Faker $faker) {
      $articles = factory(\App\Model\Article::class, 3)-&gt;make([\App\Model\Article::FINE_ID =&gt; $fine-&gt;id]);
      // TEST WITH SAVEMANY: $fine-&gt;saveMany(factory(\App\Model\Article::class, 10)-&gt;make());
      // SAME WITH CREATEMANY
      // TEST WITH HYDRATE: $multa-&gt;articles()-&gt;hydrate([$article]);
      // $multa-&gt;load('articles');
  });
  </code></pre>
  <p>Just to make a point I have tried different roads but, I admit, I am a bit lost.</p>
  <p>Basically I end up with the classical</p>
  <blockquote>
  <p>Illuminate\Database\QueryException: SQLSTATE[42S02]: Base table or view not found</p>
  </blockquote>
  <p>error, so I am still accessing the database.</p>
  <p>Now, I am starting to think that factories are a proper choice only if at the end one is going to store data on the database (I am sure that <code>saveMany()</code> is going to work if I use <code>create()</code> and not <code>make()</code>).</p>
  <p>Can you please give me an hint on how to accomplish this task? If factories are not the right way to do it I am more than open to change my choice, too.</p>
  <p>Thanks in advance!
  Lorenzo</p>