title: Laravel Eloquent Database Relationships and Foreign Keys
body: <p>I have two tables:</p>
  
  <pre><code>use Illuminate\Database\Migrations\Migration;
  
  class CreateTransactionsTable extends Migration {
  
          /**
           * Run the migrations.
           *
           * @return void
           */
          public function up()
          {
                  Schema::create('transactions', function($table) {
                          $table-&gt;increments('id');
                          $table-&gt;bigInteger('amount');
                          $table-&gt;integer('from');
                          $table-&gt;integer('to');
                          $table-&gt;integer('type');
                          $table-&gt;timestamps();
                  });
  
                  Schema::create('transaction_types', function($table) {
                          $table-&gt;increments('id');
                          $table-&gt;string('name');
                  });
          }
  
          /**
           * Reverse the migrations.
           *
           * @return void
           */
          public function down()
          {
                  Schema::dropIfExists('transactions');
                  Schema::dropIfExists('transaction_types');
          }
  }
  </code></pre>
  
  <p>_</p>
  
  <pre><code>// app/models/Transactiones.php
  class Transaction extends Eloquent {
          public function type()
          {
                  return $this-&gt;belongsTo('TransactionType');
          }
  }
  </code></pre>
  
  <p>_</p>
  
  <pre><code>// app/models/TransactionTypes.php
  class TransactionType extends Eloquent {
          public function Transactions()
          {
                  return $this-&gt;hasMany('Transaction', 'type');
          }
  }
  </code></pre>
  
  <p>I seeded transaction_types with (1, 'deposit') Now I'm creating a transactions and I want to set the FK of type to the id in transaction_types:</p>
  
  <p>(The code below does not work..)</p>
  
  <pre><code>if (0 == Transaction::where('from', $tmpData-&gt;refID)-&gt;count()) {
          $t = new Transaction();
          $t-&gt;amount = $tmpData-&gt;amount;
          $t-&gt;from = $tmpData-&gt;refID;
          $t-&gt;to = $tmpData-&gt;ownerID1;
  
          // fails
          $t-&gt;type = TransactionType::find(1); // desposit
  
          // fails
          //$t-&gt;types()-&gt;insert(TransactionType::find(1)); // desposit
  
          // If it I do it this way it DOES work, but this seems backwards
          //TransactionType::find(1)-&gt;Transactions()-&gt;save($t);
  
          $t-&gt;save();
  }
  </code></pre>
  
  <p>What I'm I doing wrong? It's just a simple lookup table so when I'm done, I can simply do $transaction->type()->name and display the name.</p>
  
  <p>Also, I'm very new Laravel, so any suggestions on better code is welcome.</p>