I’m creating a small webshop where users can create orders and sellers can see the orders. I have defined relationships but the related functions are null. This is how my tables looks like in phpmyAdmin https://imgur.com/a/C2PSmFt
This is how I have defined relationships in my models.
User.php
public function sellerOrders()
{
return $this->hasMany(Order::class);
}
Order.php
public function user()
{
return $this->belongsTo('AppUser', 'seller_id');
}
public function products()
{
return $this->belongsToMany('AppProduct')->withPivot('quantity','total','Subtotal');
}
public function productInfo()
{
return $this->belongsTo('AppProduct');
}
public function orderInfo()
{
return $this->belongsTo(OrderProduct::class, 'seller_id');
}
This is my function in controller
$orders = Auth::user()->sellerOrders()->with('productInfo','orderInfo')->get();
When I dd($orders)
, this is what i get
Collection {#305 ▼
#items: array:1 [▼
0 => Order {#286 ▼
#table: "orders"
#fillable: array:5 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▼
"id" => 9
"user_id" => 1
"shipping_email" => "878888"
"shipping_name" => "hattta"
"shipping_city" => "kljjdjd"
"shipped" => 0
"created_at" => "2019-07-05 01:33:58"
"updated_at" => "2019-07-05 01:33:58"
]
#original: array:8 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:2 [▼
"productInfo" => null
"orderInfo" => null
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
How can I show productInfo
and orderInfo
? Your help is really appreciated.
2
Answers
Because You have in relation return
hasMany
=> in orders you will have an array and since you queried it already, you have to query each item like so:If you take a look at the attributes on the Order model from your dump, there is no field
seller_id
:You need to either add a
seller_id
field to the model and add the value to the database, or, perhaps easier, change your relations on the Order model so that the foreign key isuser_id
instead ofseller_id
.Once you fix this, you should see a value for your
**user**
on the Order. So if you loop through$orders
, you can do $order->user and it should return the user for the order.Same thing for your productInfo. There is no
product_id
on the Order model, and because of the non-conventional name (i.e. it’s not just ‘product()
‘), you will need to specify the foreign key in the relationship method on the Order model. Also, don’t forget to add theproduct_id
to the Order model as fillable.Same problem applies to your
orderInfo()
method – there is noseller_id
on the order model to provide the relationship – same fix could apply as above.