“我要做的是更新主表的摘要字段。”
我有三张桌子,三餐,订单和order_items。Meal hasMany Order hasMany OrderItem
class Meal extends Eloquent {
protected $table = 'meals';
protected $primaryKey = 'id';
public function orders() {
return $this->hasMany('Order', 'meal_id');
}
}
class Order extends Eloquent {
protected $table = 'orders';
protected $primaryKey = 'id';
public function meal() {
return $this->belongsTo('Meal', 'meal_id');
}
public function orderItems() {
return $this->hasMany('OrderItem', 'order_id');
}
}
class OrderItem extends Eloquent {
protected $table = 'order_items';
protected $primaryKey = 'id';
public function order() {
return $this->belongsTo('Order', 'order_id');
}
}
在我的控制器中,我使用批量赋值来插入这3个表
$meal = Meal::create($mealData);
$order = Order::create($orderData);
$orderItem = OrderItem::create($orderItemData);
...
//I don't know what to do next
如果我在餐饮模型中有一个函数,例如updateSummary(),在插入这3个表之后,如何调用updateSummary(),以及如何引用刚刚插入的当前meal_id?
这就是我一直在做的事情
public function updateSummary() {
//using relationship
$orders = $this->orders();
//then use $orders to do some calculation
}
我可以从我的控制器调用它吗?
//after insert those 3 tables
$meal->updateSummary();
正如我上面提到的,我想要的是在将数据插入到子表中之后更新主表(餐饮)的摘要字段(amount_sum),但我不知道该往哪个方向走,请建议,谢谢。
发布于 2013-08-15 21:54:25
获取meal_id
create()
函数creates the instance and also, importantly,
$meal = Meal::create($mealData);
因此,在这一点上,要获得$meal_id
,您只需将其从模型中提取出来:
$meal_id = $meal->meal_id;
这同样适用于您的$order
和$orderItem
的新实例。这有意义吗?
https://stackoverflow.com/questions/18252359
复制相似问题