在多个到多个数据透视表中获取每个实例的总出现次数

时间:2013-12-11 17:56:45

标签: laravel many-to-many laravel-4

让我们说我们有两种模式,优惠券和产品的多对多关系

class Coupon extends \Eloquent {

  protected $table = 'coupons';

    public function products()
    {
        return $this->belongsToMany('Product');
    }
}

class Product extends \Eloquent {

  protected $table = 'products';

    public function coupons()
    {
        return $this->belongsToMany('Coupon');
    }
}

使用数据透视表只配对两个模型:

table: coupon_product
coupon_id, product_id

在数据透视表中,有可能(在我的情况下有效)有多个相同的对,即

coupon_id | product_id
    1            1
    1            1
    1            2
    2            1
    3            3
    3            3

使用(例如)产品ID = 1获取总优惠券的最佳方法是什么,计算数据透视表中所有优惠券的出现次数?目标是在视图中传递$ coupons数组,以显示使用产品ID = 1注册的所有优惠券的列表。

在数据透视表的上述示例中,它将是:

  1. 优惠券1
  2. 优惠券1
  3. 优惠券2

1 个答案:

答案 0 :(得分:0)

如果您正在使用数据库查询构建器:

DB::table('coupons')->where('product_id', 1)->get();

如果使用Eloquent ORM:

Product::find(1)->coupons;

使用Eloquent ORM时,如果您希望添加一些加载优惠券的限制,可以使用以下内容:

Product::find(1)->coupons()->where(some_condition)->get();