首页 > 解决方案 > Laravel Eloquent 在 belongsToMany 关系上返回一个空集合

问题描述

更新:这里提到的问题是由 XAMPP 使用 MariaDB 而不是 MySQL 引起的。我已按照此处的答案将其切换到 MySQL,它就像一个魅力。


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

我有 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

标签: phpmysqllaraveleloquent

解决方案


为连接表创建第三个模型,并添加两个关系。它会起作用的。

class ProductSpecialOffer extends Model
{
   public function products() {
       return $this->belongsTo(Product::class);
   }

   public function specialOffers() {
       return $this->belongsTo(SpecialOffer::class);
   }
}

推荐阅读