我有两张桌子:
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现在我正在创建一个事务,我想在transaction_types中将类型的FK设置为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,所以欢迎任何有关更好代码的建议。
答案 0 :(得分:0)
这不是倒退,这是用雄辩的方式做你想做的事的正确方法。
$type = TransactionType::find(1);
$type->transactions()->save(new Transaction(array(
'amount' => $tmpData->amount,
'from' => $tmpData->refID,
'to' => $tmpData->ownerID1
)));