使产品只能购买一次

时间:2018-07-14 09:19:44

标签: php laravel eloquent

您好,我尝试制造产品的人只能购买一次,所以我做到了

productsTable: id,name,desc,price,onlyOnce(Boolean 0-1)

我也创建了数据透视表:orders: user_id,product_id

我尝试以下代码:

public function showProducts(Category $category, User $user) {

    $products = $category->products()->where('onlyOnce', 1)->pluck('id')->toArray();
    $userOrders = $user->orders()->pluck('user_Id')->toArray();
    $missProducts = array_intersect($userOrders, $products);


    $extras = $category->products()->whereNotIn('id', $missProducts)->get();


    return view('products.category',compact('extras'));
}

但是行不通,有些想法该怎么做?

(如果您需要的是我的型号) Product.php

 class Product extends Model
 {
  protected $fillable = [];

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function categories() {
   return $this->belongsToMany(Category::class);
}

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function orders(){
    return $this->hasMany(Order::class);
}

}

Order.php

class Order extends Model
{
/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function user()
{
    return $this->belongsTo(User::class);
}

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function product(){
    return $this->belongsTo(Product::class);
}

/**
 * @return int
 */
public function getTotalPrice() {

    $orders = self::with('product')->get();
    $total = $orders->pluck('product')->sum('price');

    return $total;
}

}

User.php 类用户扩展Authenticateable {

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name'];

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function orders()
{
    return $this->hasMany(Order::class);
}

}

使用该代码,它返回空数组,我不知道为什么,所以,如果您有一些想法,请问如何解决该问题或键入什么新代码来回答问题!多谢指教,平安! ;)

1 个答案:

答案 0 :(得分:0)

您设置的数据库有点奇怪,我会做的很不同,但是以下代码应该检索用户未购买的所有产品。让我知道它是否有效。

$productID = 123;
$userID = 10;
$purchased = $orders->select('product_id')->where('user_id', $userID)->toArray();

$notPurchased = $productsTable->whereNotIn('id',$purchased)->get();

然后您可以将$ notPurchased传递给视图,并使用foreach()循环在其上循环以获取每个未购买的产品ID。