Reputation: 342
I have 3 tables: Order, Contract, Order_contract.
I created another table (order_contract) to join Orders, and Contracts. The migration is below:
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');
}
I want to insert data into my tables.
1. Insert the new contract (at the insertion I know the $contract->id
)
2. If more then one order was attached to one order then insert every single relation into the order_contract table
Models:
**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');
}
}
How can I use in this situation Laravels hasOne(),hasMany(),belongsTo(),belongsToMany() functions?
Upvotes: 2
Views: 3327
Reputation: 4801
You are creating an intermediate table when you're using the OneToMany relationship. You only have to do so when creating a ManyToMany relationship.
Remove the order_contact table, and add a column "contract_id" on your orders table (you can optionally make it nullable, so an order doesn't have to have a contract).
Then you can add a function to your Contract
model
class Contract extends Eloquent {
public function orders()
{
return $this->hasMany('Order');
}
}
and to your Order
model
class Order extends Eloquent {
public function contract()
{
return $this->belongsTo('Contract');
}
}
Then you can do something like this:
$order1 = new Order;
$order2 = new Order;
$contract = new Contract;
$contract->orders()->saveMany([$order1, $order2]);
Check out the docs on Attaching A Related Model
If you insists on doing it through your intermediate table you can do it like so:
class Contract extends Eloquent {
public function orders()
{
return $this->hasManyThrough('Order', 'Contract', 'order_id', 'contract_id');
}
}
Note that Eloquent assumes that you have an intermediate model.
There is no BelongsToManyThrough function in Laravel though, so you're going to have to write your own method. The hasManyThrough is just a shortcut and is not meant to be used this way...
I'd still advice against doing it this way.
Upvotes: 1