I'm not getting an error message from this, but Laravel 5.1 will not assign values to a foreign key column in the OrderDetails
table. I've tried multiple different calls and can't figure out what's wrong.
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);
}
The relationship bewtween OrderHeader and OrderDetails are as follows.
<?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');
}
}
And:
<?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');
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire