Php Laravel雄辩的数据库关系和外键
我有两张桌子:Php Laravel雄辩的数据库关系和外键,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我有两张桌子: use Illuminate\Database\Migrations\Migration; class CreateTransactionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() {
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');
}
}
_
_
我使用(1,'存款')作为交易类型的种子,现在我正在创建一个交易,我想将类型的FK设置为交易类型中的id:
(下面的代码不起作用.)
我做错了什么?这只是一个简单的查找表,所以当我完成后,我可以简单地执行$transaction->type()->name并显示名称
另外,我是非常新的Laravel,所以任何关于更好代码的建议都是欢迎的。这不是倒退,这是使用雄辩来做你想做的事情的正确方法
$type = TransactionType::find(1);
$type->transactions()->save(new Transaction(array(
'amount' => $tmpData->amount,
'from' => $tmpData->refID,
'to' => $tmpData->ownerID1
)));
如果我必须FK,我会怎么做?当你说外键时,你是指DB上的真正外键约束吗?如果您的意思是,如何将其分配给模型,您不需要,eloquent会为您这样做。TransactionType只是事务的类型查找表,将有其他链接表。我想将“to”链接到用户表(它是用户id)。我该怎么把它加进去?
// app/models/TransactionTypes.php
class TransactionType extends Eloquent {
public function Transactions()
{
return $this->hasMany('Transaction', 'type');
}
}
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();
}
$type = TransactionType::find(1);
$type->transactions()->save(new Transaction(array(
'amount' => $tmpData->amount,
'from' => $tmpData->refID,
'to' => $tmpData->ownerID1
)));