【发布时间】:2015-03-16 15:50:43
【问题描述】:
我有 3 个表:Order、Contract、Order_contract。
- 一份合约(可以)有(因为多个订单最终价格可以 结合在一起)多个订单
- 但是一个订单可以有一个 合同
我创建了另一个表 (order_contract) 来连接订单和合同。 迁移如下:
public function up()
{
Schema::create('contracts', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
});
Schema::create('orders', function(Blueprint $table)
{
$table->increments('id');
$table->integer('price');
$table->timestamps();
});
Schema::create('order_contract', function(Blueprint $table)
{
$table->integer('order_id')->unsigned();
$table->foreign('order_id')->references('id')->on('orders');
$table->integer('contract_id')->unsigned();
$table->foreign('contract_id')->references('id')->on('contracts');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('contracts');
Schema::drop('orders');
Schema::drop('order_contract');
}
我想将数据插入到我的表中。
1. 插入新合同(插入时我知道$contract->id)
2. 如果一个订单附加了多个订单,则将每个关系插入到 order_contract 表中
型号:
**Order.php**
class Order extends Eloquent{
protected $fillable = ['price'];
public function contract(){
return $this->belongsTo('Contract');
}
}
**Contract.php**
class Contract extends Eloquent{
public function orders(){
return $this->hasMany('Order','order_contract','order_id','contract_id');
}
}
在这种情况下如何使用 Laravel 的 hasOne(),hasMany(),belongsTo(),belongsToMany() 函数?
【问题讨论】:
标签: join laravel-4 relationship belongs-to