让我们说,我们有很多很多关系的两种模式,优惠券和产品。
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数组,以显示所有注册为product = 1的优惠券的列表。
在上述枢轴表示例中,如下所示:
发布于 2013-12-11 21:22:16
如果您使用的是DB查询生成器:
DB::table('coupons')->where('product_id', 1)->get();如果使用雄辩的ORM:
Product::find(1)->coupons;在使用雄辩的ORM时,如果希望添加一些加载优惠券的约束,可以使用以下方法:
Product::find(1)->coupons()->where(some_condition)->get();https://stackoverflow.com/questions/20526507
复制相似问题