class Order extends Elequent{
protected $table = 'order';
const CREATED_AT = "createdAt";
const UPDATED_AT = "updatedAt";
protected $with = array('orderItem', 'address');
public function orderItem(){
return $this->hasMany("OrderItem","orderId");
}
public function address(){
return $this->hasOne("OrderAddress","orderId","id");
}
}
//in controller
$order = Order::findOrFail($orderId);
echo $order;
使用上面的类将序列序列化为json时,如何将order_item命令为orderItem(我喜欢骆驼案例而不是蛇案例)
{
"id": 1,
"userId": 1,
"createdAt": "2015-04-30 12:08:26",
"deletedAt": "0000-00-00 00:00:00",
"updatedAt": "2015-04-30 12:08:26",
"state": "activated",
"deliveryNote": null,
"order_item": [
{
"id": 1,
"specialProductId": 29,
"volume": 750,
"quantity": 2,
"price": "543.38",
"orderId": 1,
"updatedAt": "2015-04-30 12:08:26",
"createdAt": "2015-04-30 12:08:26"
}
],
"address": null
}
答案 0 :(得分:7)
在模型中,将$snakeAttributes
属性设置为false。这将使属性在生成数组时不会被蛇形化。
class Order extends Elequent {
public static $snakeAttributes = false;
}
答案 1 :(得分:2)
您可以复制/重命名对象属性并取消设置旧属性。
//in controller
$order = Order::findOrFail($orderId);
$order->orderItem = $order->order_item;
unset($order->order_item);
echo $order;
为了更好地使用,您可以将此方法放在Base模型上,
public function toArrayCamel()
{
$array = $this->toArray();
foreach($array as $key => $value)
{
$return[camel_case($key)] = $value;
}
return $return;
}
以及稍后在你的控制器上,
$order = Order::findOrFail($orderId);
return Response::json( $order->toArrayCamel() );