0

我有两张桌子:

use Illuminate\Database\Migrations\Migration;

class CreateTransactionsTable extends Migration {

        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
                Schema::create('transactions', function($table) {
                        $table->increments('id');
                        $table->bigInteger('amount');
                        $table->integer('from');
                        $table->integer('to');
                        $table->integer('type');
                        $table->timestamps();
                });

                Schema::create('transaction_types', function($table) {
                        $table->increments('id');
                        $table->string('name');
                });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
                Schema::dropIfExists('transactions');
                Schema::dropIfExists('transaction_types');
        }
}

_

// app/models/Transactiones.php
class Transaction extends Eloquent {
        public function type()
        {
                return $this->belongsTo('TransactionType');
        }
}

_

// app/models/TransactionTypes.php
class TransactionType extends Eloquent {
        public function Transactions()
        {
                return $this->hasMany('Transaction', 'type');
        }
}

我用 (1, 'deposit') 播种了 transaction_types 现在我正在创建一个交易,我想将类型的 FK 设置为 transaction_types 中的 id:

(下面的代码不起作用..)

if (0 == Transaction::where('from', $tmpData->refID)->count()) {
        $t = new Transaction();
        $t->amount = $tmpData->amount;
        $t->from = $tmpData->refID;
        $t->to = $tmpData->ownerID1;

        // fails
        $t->type = TransactionType::find(1); // desposit

        // fails
        //$t->types()->insert(TransactionType::find(1)); // desposit

        // If it I do it this way it DOES work, but this seems backwards
        //TransactionType::find(1)->Transactions()->save($t);

        $t->save();
}

我做错了什么?这只是一个简单的查找表,所以当我完成后,我可以简单地执行 $transaction->type()->name 并显示名称。

另外,我是 Laravel 的新手,欢迎对更好的代码提出任何建议。

4

1 回答 1

0

这不是倒退,这是使用 eloquent 做你想做的事情的正确方法。

$type = TransactionType::find(1);

$type->transactions()->save(new Transaction(array(
    'amount' => $tmpData->amount,
    'from'   => $tmpData->refID,
    'to'     => $tmpData->ownerID1
)));
于 2013-11-06T20:51:08.970 回答