我有一个优惠券模型,它与产品模型(有枢轴表等等)有很多关系。我创建了一些本地范围,以便只获得可用的优惠券,并且只获得确定类别的优惠券:
public function scopeAvailable($query)
{
return $query->where('available', '>', 0);
}
public function scopeOfCategory($query, $category)
{
return $query->join('categories', 'categories.id', '=', 'coupons.category_id')
->where('categories.slug', $category);
}
我想急切地装载所有可用的某些类别的优惠券与他们各自的产品。所以我在做:
$coupons = Coupon::with('products')->available()->ofCategory($category)->paginate(20);
如果我打电话给$coupons->first()
,我可以看到关于优惠券的信息。但是如果我调用$coupons->first()->products
,就会得到一个空数组。
如果我对->ofCategory($category)
部分进行评论,它将如预期的那样工作。
这是我的模特:
class Coupon extends Model
{
public function products()
{
return $this->belongsToMany('App\Product');
}
...
}
class Product extends Model
{
public function coupons()
{
return $this->belongsToMany('App\Coupon');
}
...
}
我用的是Laravel 5.2。我做错了什么?
编辑:,我的分类看起来有点问题。如果我试着获得“其他”类别的优惠券,我就会得到预期的优惠券。如果我试图获得“电子”类的优惠券,我会得到一张没有产品的优惠券。我很确定我有“电子产品”和“其他”产品的优惠券。
如果我转储Category::where('slug', '=', 'electronics')->first()
...
protected 'attributes' =>
array (size=3)
'id' => int 1
'name' => string 'Electronics' (length=11)
'slug' => string 'electronics' (length=11)
...
如果我抛弃Category::where('slug', '=', 'other')->first()
:..。受保护的‘属性’=>数组(size=3) 'id‘=> int 2’名称‘=> string 'other’(length=5) 'slug‘=> string 'Other’(length=5) .
编辑2:我创建了另一个带有“其他”类别的优惠券,因此我有两张带有此类别的优惠券。当我打印优惠券时,它会显示第一张优惠券两次。
发布于 2016-01-15 13:49:47
表coupons
| id | name | available | category_id |
|----|------------|-----------|-------------|
| 1 | Coupon #1 | 1 | 1 |
| 2 | Coupon #2 | 1 | 1 |
| 3 | Coupon #3 | 1 | 1 |
表products
| id | name |
|----|-------------|
| 1 | Product #1 |
| 2 | Product #2 |
| 3 | Product #3 |
表coupon_product
| id |product_id| coupon_id |
|----|----------|-----------|
| 1 | 1 | 1 |
| 2 | 2 | 1 |
表categories
| id | slug |
|----|-------------|
| 1 | category-1 |
| 2 | category-2 |
| 3 | category-3 |
Product.php
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function coupons()
{
return $this->belongsToMany('App\Coupon');
}
}
Coupon.php
class Coupon extends Model
{
public function products()
{
return $this->belongsToMany('App\Product');
}
public function scopeAvailable($query)
{
return $query->where('available', '>', 0);
}
public function scopeOfCategory($query, $category)
{
return $query->join('categories', 'categories.id', '=', 'coupons.category_id')
->where('categories.slug', $category);
}
}
最后当我跑的时候:
$coupons = App\Coupon::with('products')->available()->ofCategory('funny')->first();
dd($coupons->products);
我明白了:
这是正确的。你能发布更多关于你当前项目状态的详细信息吗?
https://stackoverflow.com/questions/34811730
复制相似问题