【发布时间】:2019-11-15 14:53:52
【问题描述】:
我正在创建一个小型网上商店,用户可以在其中创建订单,卖家可以查看订单。我已经定义了关系,但相关函数为空。这就是我的表格在 phpmyAdmin https://imgur.com/a/C2PSmFt
中的样子这就是我在模型中定义关系的方式。
User.php
public function sellerOrders()
{
return $this->hasMany(Order::class);
}
Order.php
public function user()
{
return $this->belongsTo('App\User', 'seller_id');
}
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity','total','Subtotal');
}
public function productInfo()
{
return $this->belongsTo('App\Product');
}
public function orderInfo()
{
return $this->belongsTo(OrderProduct::class, 'seller_id');
}
这是我在控制器中的功能
$orders = Auth::user()->sellerOrders()->with('productInfo','orderInfo')->get();
当我dd($orders)时,这就是我得到的
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 [▶]
}
]
}
如何显示productInfo 和orderInfo?非常感谢您的帮助。
【问题讨论】:
-
您在
user()和orderInfo()中都使用seller_id作为外键。而且您还没有为productInfo()放置外键。只是product_info_id吗? -
我确实将
seller_id放入productInfo()并得到null。 @newUserName02 -
seller_id应该只是其中一个的外键,我猜是用户。您需要为其他 2 填写正确的外键。
标签: php laravel laravel-5 eloquent