这是关于电子商务平台的。

我有2个数据表和1个联接表,用于多对多联接。这个想法是为了让产品在任何给定的时间运行许多特殊优惠。



桌子

产品展示

+-------+-------------------------------+
| id    | name                          |
+-------+-------------------------------+
| 10001 | Apple iPhone 11               |
| 10002 | Samsung Galaxy S11            |
+-------+-------------------------------+


特别优惠

+----+-------------------------------+
| id | name                          |
+----+-------------------------------+
|  1 | Awesome Offer                 |
|  2 | Year End Offer                |
+----+-------------------------------+


product_special_offer

+------------+------------------+----------+
| product_id | special_offer_id | discount |
+------------+------------------+----------+
| 10001      | 1                | 10.0     |
| 10002      | 2                | 12.5     |
+------------+------------------+----------+




楷模

由于要求是many-to-many关系,因此我在模型中使用belongToMany方法。

产品

class Product extends Model
{
    public function specialOffers()
    {
        return $this->belongsToMany(SpecialOffer::class)->withPivot('discount');
    }
}


特别优惠

class SpecialOffer extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot('discount');
    }
}




控制者

以下是控制器代码段。

产品控制器

class ProductController extends Controller
{
    public function index()
    {
        $product = Product::find(10001);

        dd($product->specialOffers);
    }
}




结果

以下是Laravel返回的内容。

Collection {#610 ▼
  #items: []
}


它所运行的查询在下面提到。

select `special_offers`.*, `product_special_offer`.`product_id` as `pivot_product_id`, `product_special_offer`.`special_offer_id` as `pivot_special_offer_id`, `product_special_offer`.`discount` as `pivot_discount` from `special_offers` inner join `product_special_offer` on `special_offers`.`id` = `product_special_offer`.`special_offer_id` where `product_special_offer`.`product_id` = 10001

最佳答案

请更改您的型号

产品

class Product extends Model
{
    public function specialOffers()
    {
        return $this->belongsToMany('App\SpecialOffer','product_special_offer','special_offer_id','product_id ')
    }
}


特别优惠

class SpecialOffer extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\SpecialOffer','product_special_offer','product_id','special_offer_id');
    }
}

10-08 04:45