【问题标题】:Laravel Mass Assignment Using JSON使用 JSON 的 Laravel 质量分配
【发布时间】:2017-05-15 16:27:34
【问题描述】:

这些是我的模型:

订单:

class orders extends Model
{
protected $table = 'orders';
public function getItems()
{

    return $this->hasMany('App\order_items');
}


protected $fillable = [
   'subtotal','discount_amount','after_discount_price','mechanic_id','owned_cars_id','primary_id','promo_code_string',
    'order_status_id'
];

}

订购商品:

class order_items extends Model
{
protected $table = 'order_items';


protected $fillable = [
    'order_primary_id','primary_id','service_id','service_name','service_thumbnail','service_orignal_price','discount_amount',
    'after_discount_price','service_description','service_classification'
];
}

这是 JSON 结构

{
  "orderID": null,
  "PromoId": 0,
  "subtotal": 2500,
  "discount": 12,
  "discountPrice": 3500,
  "mechanic_id": null,
  "ownedcarId": 1,
  "ownedCarServerId": 0,
  "order_status_id": 1,
  "order_items": [
    {
      "order_item_server_id": null,
      "order_id": null,
      "order_primary_id": 1,
      "primary_id": 1,
      "service_id": 1,
      "service_name": "Car Wash",
      "service_thumbnail": "asd",
      "service_original_price": 2500,
      "discount_amount": 20,
      "after_discount_price": 20,
      "service_description": "description",
      "service_classification": 1,
      "service_sub_items":0 

    }
  ]
}

对于新订单,此代码可以正常工作:

$order = new order();
$order->user_id = 123;
$order->fill($request->all()); 
$order->save();

有什么方法可以使用 $request->all() 将大量可分配数据直接保存在关键“订单项”中?还是我必须一件一件的去做?

【问题讨论】:

    标签: php json laravel eloquent


    【解决方案1】:

    如果您的请求中有多余的字段不应该出现在您的模型中。你可以这样做:

    $input = $request->only(['username', 'password']);
    $input = $request->only('username', 'password');
    
    $input = $request->except(['credit_card']);
    $input = $request->except('credit_card');
    

    取自https://laravel.com/docs/5.4/requests的“检索输入数据的一部分”

    【讨论】:

    【解决方案2】:

    你可以试试:

    foreach($request->order_items as $item){
       $orderItem = new OrderItem($item);
       $orderItem->save();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多