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?
source to share
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
source to share