[英]How to use Laravel relationships it correctly?
I have the following table structure:我有以下表结构:
users:
id
name
products:
id
name
orders:
id
user_id
product_id
paid (boolean)
order_items:
order_id
product_id
Using relationships, what would be the best way to get all the products that user 1 bought and paid for?使用关系,获得用户 1 购买和支付的所有产品的最佳方式是什么? Also, how can I pass a product ID, and check if user 1 has paid for this product?
另外,如何传递产品 ID,并检查用户 1 是否已为该产品付款?
Add user_id to order_items table, this will make things easier.将user_id添加到order_items表中,这将使事情变得更容易。 Then you can add necessary relationships to your models:
然后你可以为你的模型添加必要的关系:
User:用户:
public function orders(): HasMany
{
return $this->hasMany(Order::class);
}
public function paidOrders(): HasMany
{
return $this->hasMany(Order::class)
->where('paid', true);
}
public function products(): BelongsToMany
{
return $this->belongsToMany(
Product::class,
'order_items',
'user_id',
'product_id'
);
}
public function paidProducts(): BelongsToMany
{
return $this->products()
->whereRelation('orders', 'paid', true);
}
public function hasPaidForProduct(Product|string $product): bool
{
if($product instanceof Product) {
$product = $product->getKey();
}
return $this->paidProducts()
->wherePivot('product_id', $product)
->exists();
}
Product:产品:
public function orders(): BelongsToMany
{
return $this->belongsToMany(
Order::class,
'order_items',
'product_id',
'order_id'
);
}
public function users(): BelongsToMany
{
return $this->belongsToMany(
User::class,
'order_items',
'product_id',
'user_id'
);
}
Order:命令:
public function products(): BelongsToMany
{
return $this->belongsToMany(
Product::class,
'order_items',
'order_id',
'product_id'
);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
Creating an order would be like this:创建订单将如下所示:
$user = $request->user();
$products = ... // e.g. Cart::getItems();
$orderData = [
'paid' => false,
...
];
$attachData = [];
// Here, we are preparing order products and the additional data,
// aka user_id, for order_items table. The table will be like this:
// +----------+------------+---------+
// | order_id | product_id | user_id |
// +----------+------------+---------+
// | 1 | 1 | 1 |
// | 1 | 2 | 1 |
// | 1 | 3 | 1 |
// +----------+------------+---------+
foreach($products as $product) {
$attachData[$product->id] = [
'user_id' => $user->id,
];
}
$order = DB::transaction(function() use ($user, $orderData, $attachData) {
$order = $user->orders()
->create($orderData);
$order->products()
->attach($attachData);
return $order;
});
Then;然后;
// All products that the user has ordered.
$user->products;
// All products that the user has ordered and paid for.
$user->paidProducts;
$inquiredProduct = Product::findOrFail(1);
$user->hasPaidForProduct($inquiredProduct) // true/false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.