Laravel keep one for many relationships

I have the following relationship established in Laravel:

OrderStatus Model
  - hasMany('Order')

 Order Model
  - 'belongsTo('OrderStatus');

      

The database is configured with table orders

and table order_statuses

. The table orders

has a field for order_status_id

.

When I save the order, I manually set order_status_id

by selecting the appropriate order status model, for example:

$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order->order_status_id = $status->id;
$order->save();

      

I am wondering if there is a built-in feature and not a order_status_id

manual tweak . I've read about "Attaching a Linked Model" and "Associating Models" in the Laravel docs, but I can't figure out if they are appropriate for my use. I think the problem is due to the fact that I am directly working with the child model (order) and trying to set its parent. Is there a function for this?

+3


source to share


2 answers


You can of course do this:

$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order = new Order;
$order->status()->associate($status);
$order->save();

      



( status()

is a relationship that belongs to a relationship. You may need to customize this name)

+14


source


The correct way to save the relationship for a new linked model is as follows:

$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail(); $order = new Order; $status->order()->save($order);



Documentation: http://laravel.com/docs/4.2/eloquent#inserting-related-models

+6


source







All Articles