I have the following relationships set up in Laravel:
OrderStatus Model
- hasMany('Order')
Order Model
- 'belongsTo('OrderStatus');
The database is set up with an orders
table and an order_statuses
table. The orders
table has a field for order_status_id
.
When I save an Order, I manually set the order_status_id
by fetching the appropriate Order Status model, like this:
$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order->order_status_id = $status->id;
$order->save();
I'm wondering if there is a built in function to do this rather than setting the order_status_id
manually. I've read about "Attaching a related model", and "Associating Models" in the Laravel docs, but I can't figure out if these fit my use case. I think the issue I'm having is that I'm working directly with the child model (the order), and trying to set it's parent. Is there a function for this?
Sure you can do this:
$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order = new Order;
$order->status()->associate($status);
$order->save();
(status()
is the belongsTo relation. You might need to adjust that name)
The correct way, to save a relationship for a new related model is as follows:
$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order = new Order;
$status->order()->save($order);
Documentation link : http://laravel.com/docs/4.2/eloquent#inserting-related-models
来源:https://stackoverflow.com/questions/27828476/laravel-save-one-to-many-relationship