Laravel不将数据添加到数据库中的外键列值

时间:2016-04-19 07:39:09

标签: php laravel laravel-5 laravel-5.1

我没有从中收到错误消息,但Laravel 5.1不会将值分配给OrderDetails表中的外键列。我尝试了多个不同的电话,但无法弄清楚哪些是错的。

    public function orderProduct(Request $request){
        //Try and find the current incomplete order. If find fails, then create new order.
        $order;
        try{
            $order = OrderHeader::where("UserID","=", Auth::user()->id)
            ->where('OrderCompleted', '=', false)->firstOrFail();
        }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
            $order = new OrderHeader;
            //find user
            $id = Auth::user()->id;
            $user = User::find($id);
            //associate user
            $order->user()->associate($user);
            //mark order incomplete
            $order->OrderCompleted = false;
            $order->OrdersShipped = false;
            $order->save();
        }
        //find matching or create new order detail. Update or add details and ade it to order. 
       /**
        *Somewhere in here is the problem(s)
        *The four or so lines I've commented out are all different attempts
        *to get the value in the database.
        */
        $orderDetail;
        $productID = $request->input("pID");
        try{
            $orderDetail = $order->orderDetails()->where("ProductID", "=", $productID)->firstOrFail(); 
            //add feilds assignment
        }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
            $orderDetail = new OrderDetail;
//  $orderDetail->orderHeader()->associate(OrderHeader::find($order->OrderID));
            $orderDetail->QtyOrdered = $request->input("qty");
            $orderDetail->product()->associate(Product::find($productID));
//          $orderDetail->OrderHeaderID = $order->OrderID;
//          $orderDetail->orderHeader()->associate($order);
        //  $orderDetail->save();
        //$order->orderDetails()->save($orderDetail);
            //$orderDetail = OrderDetail::create(['OrderHeaderID' => $order->OrderId,'ProductID'=> $request->input("pID"), 'QtyOrdered' => $request->input("qty")]);
        }
        return $orderDetail;    
//  ProductController::cartView($order);
    }

OrderHeader和OrderDetails之间的关系如下:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrderDetail extends Model
{
    //
    protected $table = "OrderDetails";
    protected $primaryKey = "OrderDetails";
    protected $fillable = array('OrderHeaderID, ProductID, QtyOrdered');

    public function orderHeader(){
        return $this->belongsTo('App\OrderHeader', 'OrderHeaderID', 'OrderID');
    }
    public function product(){
        return $this->belongsTo('App\Product', 'ProductID', 'pID');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class OrderHeader extends Model
{
    //
    protected $table = 'OrderHeader';
    protected $primaryKey = 'OrderID';
    protected $fillable = array('ShippingID');  

    public function orderDetails(){
        return $this->hasMany('App\OrderDetail','OrderHeaderID','OrderID');
    }
    public function shippingAddress(){
        return $this->belongsTo("App\Shipping", 'ShippingID', 'ShippingID');
    }
    public function user(){
        return $this->belongsTo("App\User", 'UserID');
    }
}

编辑:使用dd($ orderDetails)查看可变内容而不尝试设置OrderHeaderID会弹出以下内容:

OrderDetail {#172 ▼
  #table: "OrderDetails"
  #primaryKey: "OrderDetails"
  #fillable: array:1 [▼
    0 => "OrderHeaderID, ProductID, QtyOrdered"
  ]
  #connection: null
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:2 [▼
    "QtyOrdered" => "1"
    "ProductID" => "7"
  ]
  #original: []
  #relations: array:1 [▼
    "product" => Product {#187 ▼
      #table: "Product"
      #primaryKey: "pID"
      #connection: null
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:8 [▼
        "pID" => "7"
        "pName" => "P1"
        "pBrand" => "pbrand"
        "pCurrentType" => "AC"
        "pVoltage" => "4.5"
        "pPrice" => "5.5"
        "pStock" => "6"
        "ImagePath" => null
      ]
      #original: array:8 [▼
        "pID" => "7"
        "pName" => "P1"
        "pBrand" => "pbrand"
        "pCurrentType" => "AC"
        "pVoltage" => "4.5"
        "pPrice" => "5.5"
        "pStock" => "6"
        "ImagePath" => null
      ]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▼
        0 => "*"
      ]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: false
  +wasRecentlyCreated: false
}

dd($orderDetail)上使用$orderDetail->orderHeader()->associate(OrderHeader::find($order->OrderID));

OrderDetail {#172 ▼
  #table: "OrderDetails"
  #primaryKey: "OrderDetails"
  #fillable: array:1 [▼
    0 => "OrderHeaderID, ProductID, QtyOrdered"
  ]
  #connection: null
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:3 [▼
    "OrderHeaderID" => null
    "QtyOrdered" => "11"
    "ProductID" => "7"
  ]
  #original: []
  #relations: array:1 [▼
    "product" => Product {#187 ▼
      #table: "Product"
      #primaryKey: "pID"
      #connection: null
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: false
  +wasRecentlyCreated: false
}

$orderDetail->OrderHeaderID = $order->OrderID;

上使用它
    OrderDetail {#172 ▼
  #table: "OrderDetails"
  #primaryKey: "OrderDetails"
  #fillable: array:1 [▼
    0 => "OrderHeaderID, ProductID, QtyOrdered"
  ]
  #connection: null
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:6 [▼
    "QtyOrdered" => "1"
    "ProductID" => "7"
    "OrderHeaderID" => null
    "updated_at" => "2016-04-20 12:53:02.000"
    "created_at" => "2016-04-20 12:53:02.000"
    "OrderDetails" => 13
  ]
  #original: array:6 [▼
    "QtyOrdered" => "1"
    "ProductID" => "7"
    "OrderHeaderID" => null
    "updated_at" => "2016-04-20 12:53:02.000"
    "created_at" => "2016-04-20 12:53:02.000"
    "OrderDetails" => 13
  ]
  #relations: array:1 [▼
    "product" => Product {#187 ▶}
  ]
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: true
}

$orderDetail->orderHeader()->associate($order);

上使用它
    OrderDetail {#172 ▼
      #table: "OrderDetails"
      #primaryKey: "OrderDetails"
      #fillable: array:1 [▼
        0 => "OrderHeaderID, ProductID, QtyOrdered"
      ]
      #connection: null
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:6 [▼
        "QtyOrdered" => "1"
        "ProductID" => "7"
        "OrderHeaderID" => null
        "updated_at" => "2016-04-20 13:00:32.000"
        "created_at" => "2016-04-20 13:00:32.000"
        "OrderDetails" => 15
      ]
      #original: array:6 [▼
        "QtyOrdered" => "1"
        "ProductID" => "7"
        "OrderHeaderID" => null
        "updated_at" => "2016-04-20 13:00:32.000"
        "created_at" => "2016-04-20 13:00:32.000"
        "OrderDetails" => 15
      ]
      #relations: array:2 [▼
        "product" => Product {#187 ▼
          #table: "Product"
          #primaryKey: "pID"
          #connection: null
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:8 [▶]
          #original: array:8 [▶]
          #relations: []
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #guarded: array:1 [▶]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
        "orderHeader" => OrderHeader {#177 ▼
          #table: "OrderHeader"
          #primaryKey: "OrderID"
          #fillable: array:1 [▼
            0 => "ShippingID"
          ]
          #connection: null
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:10 [▼
            "OrderId" => "4"
            "UserID" => "1"
            "ShippingID" => null
            "OrderCompleted" => "0"
            "OrdersShipped" => "0"
            "TotalPrice" => null
            "created_at" => "2016-04-11 14:57:25.000"
            "updated_at" => "2016-04-11 14:57:25.000"
            "CreditCard" => null
            "VerficationCode" => null
          ]
          #original: array:10 [▼
            "OrderId" => "4"
            "UserID" => "1"
            "ShippingID" => null
            "OrderCompleted" => "0"
            "OrdersShipped" => "0"
            "TotalPrice" => null
            "created_at" => "2016-04-11 14:57:25.000"
            "updated_at" => "2016-04-11 14:57:25.000"
            "CreditCard" => null
            "VerficationCode" => null
          ]
          #relations: []
          #hidden: []
          #visible: []
          #appends: []
          #guarded: array:1 [▼
            0 => "*"
          ]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
      ]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: true
    }

Using it on '$order->orderDetails()->save($orderDetail);'
OrderDetail {#172 ▼
  #table: "OrderDetails"
  #primaryKey: "OrderDetails"
  #fillable: array:1 [▼
    0 => "OrderHeaderID, ProductID, QtyOrdered"
  ]
  #connection: null
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:6 [▼
    "QtyOrdered" => "1"
    "ProductID" => "7"
    "OrderHeaderID" => null
    "updated_at" => "2016-04-20 13:17:18.000"
    "created_at" => "2016-04-20 13:17:18.000"
    "OrderDetails" => 16
  ]
  #original: array:6 [▼
    "QtyOrdered" => "1"
    "ProductID" => "7"
    "OrderHeaderID" => null
    "updated_at" => "2016-04-20 13:17:18.000"
    "created_at" => "2016-04-20 13:17:18.000"
    "OrderDetails" => 16
  ]
  #relations: array:1 [▼
    "product" => Product {#187 ▶}
  ]
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: true
}

编辑:添加有关表结构的详细信息,以防它有助于调试

CREATE TABLE [dbo].[OrderDetails] (
    [OrderDetailID] INT      IDENTITY (1, 1) NOT NULL,
    [OrderHeaderID] INT      NULL,
    [ProductID]     INT      NULL,
    [QtyOrdered]    INT      NULL,
    [created_at]    DATETIME NOT NULL,
    [updated_at]    DATETIME NOT NULL,
    PRIMARY KEY CLUSTERED ([OrderDetailID] ASC),
    CONSTRAINT [orderdetails_orderheaderid_foreign] FOREIGN KEY ([OrderHeaderID]) REFERENCES [dbo].[OrderHeader] ([OrderId]),
    CONSTRAINT [orderdetails_productid_foreign] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Product] ([pID])
);

CREATE TABLE [dbo].[OrderHeader] (
    [OrderId]         INT           IDENTITY (1, 1) NOT NULL,
    [UserID]          INT           NOT NULL,
    [ShippingID]      INT           NULL,
    [OrderCompleted]  BIT           NOT NULL,
    [OrdersShipped]   BIT           NOT NULL,
    [TotalPrice]      FLOAT (53)    NULL,
    [created_at]      DATETIME      NOT NULL,
    [updated_at]      DATETIME      NOT NULL,
    [CreditCard]      NVARCHAR (50) NULL,
    [VerficationCode] NCHAR (3)     NULL,
    PRIMARY KEY CLUSTERED ([OrderId] ASC),
    CONSTRAINT [orderheader_userid_foreign] FOREIGN KEY ([UserID]) REFERENCES [dbo].[users] ([id]),
    CONSTRAINT [fk_OrderShipping] FOREIGN KEY ([ShippingID]) REFERENCES [dbo].[Shipping] ([ShippingID])
);

1 个答案:

答案 0 :(得分:1)

试试这个:

public function orderProduct(Request $request) {
    //Try and find the current incomplete order. If find fails, then create new order.
    var $order = null;
    try{
        $order = OrderHeader::where("UserID","=", Auth::user()->id)->where('OrderCompleted', '=', false)->firstOrFail();
    }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
        $order = new OrderHeader;
        //associate user
        $order->UserID = Auth::user()->id;
        //mark order incomplete
        $order->OrderCompleted = false;
        $order->OrdersShipped = false;
        $order->save();
    }
    //find matching or create new order detail. Update or add details and ade it to order.
    /**
     *Somewhere in here is the problem(s)
     *The four or so lines I've commented out are all different attempts
     *to get the value in the database.
     */
    var $orderDetail = null;
    $productID = $request->input("pID");
    try{
        $orderDetail = $order->orderDetails()->where("ProductID", "=", $productID)->firstOrFail();
        //add feilds assignment
    }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
        $orderDetail = new OrderDetail;
        $orderDetail->OrderHeaderID = $order->OrderID;
        $orderDetail->QtyOrdered = $request->input("qty");
        $orderDetail->ProductID = $productID;
        $orderDetail->save();
        //$order->orderDetails()->save($orderDetail);
        //$orderDetail = OrderDetail::create(['OrderHeaderID' => $order->OrderId,'ProductID'=> $request->input("pID"), 'QtyOrdered' => $request->input("qty")]);
    }
    return $orderDetail;
    //ProductController::cartView($order);
}