Join Laravel一对多关系-插入

Join Laravel一对多关系-插入,join,laravel-4,relationship,belongs-to,Join,Laravel 4,Relationship,Belongs To,我有三个表格:订单,合同,订单 一个合同(可以)有(因为多个订单最终价格可以是 合并在一起)多个订单 但一份订单可以有一份 合同 我创建了另一个表(order\u contract)来连接订单和合同。 迁移情况如下: public function up() { Schema::create('contracts', function(Blueprint $table) { $table->increments('id'); $table

我有三个表格:订单合同订单

  • 一个合同(可以)有(因为多个订单最终价格可以是 合并在一起)多个订单
  • 但一份订单可以有一份 合同
我创建了另一个表(order\u 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.php**

class Order extends Eloquent{
protected $fillable = ['price'];

public function contract(){
    return $this->belongsTo('Contract');
}
}

}


在这种情况下,如何使用Laravels hasOne()、hasMany()、belongsTo()、BelongToMany()函数?

使用OneToMany关系时,您正在创建一个中间表。你只需要在建立多人关系时这样做

删除order\u contact表,并在orders表上添加一列“contract\u id”(您可以选择将其设置为null,这样订单就不必有合同)

然后,您可以向
合同
模型添加一个函数

class Contract extends Eloquent {

    public function orders()
    {
        return $this->hasMany('Order');
    }
}
class Order extends Eloquent {

    public function contract()
    {
        return $this->belongsTo('Contract');
    }
}
和您的
订单
型号

class Contract extends Eloquent {

    public function orders()
    {
        return $this->hasMany('Order');
    }
}
class Order extends Eloquent {

    public function contract()
    {
        return $this->belongsTo('Contract');
    }
}
然后你可以这样做:

$order1 = new Order;
$order2 = new Order;
$contract = new Contract;
$contract->orders()->saveMany([$order1, $order2]);
查看网上的文档


如果您坚持通过中间表执行此操作,您可以这样做:

class Contract extends Eloquent {

    public function orders()
    {
        return $this->hasManyThrough('Order', 'Contract', 'order_id', 'contract_id');
    }
}
请注意,雄辩假设您有一个中间模型

不过,Laravel中没有belongTomanyThrough函数,所以您必须编写自己的方法。hasManyThrough只是一条捷径,不打算这样使用


我仍然建议不要这样做。

我认为为关系制作另一个表是一个聪明的解决方案,不要用其他东西填充订单表,并尽可能使每个表都是基本的。你的解决方案是正确的,而且可以接受,我反对。但是你知道我怎么用中间的桌子吗?谢谢,我理解你为什么要这样做,但是我强烈建议你换一种方式考虑。我已经更新了我的答案。最后我选择了没有中间表的方式。