php - 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
解决方案
为连接表创建第三个模型,并添加两个关系。它会起作用的。
class ProductSpecialOffer extends Model
{
public function products() {
return $this->belongsTo(Product::class);
}
public function specialOffers() {
return $this->belongsTo(SpecialOffer::class);
}
}
推荐阅读
- python - Python中按位左移的最大限制
- python-3.x - 如何返回列表列表中元素的索引?
- php - Typo3:将 USER_INT 与 HMENU 的 special.value 一起使用
- snowflake-cloud-data-platform - 如何在 Snowflake 中使用 Javascript 存储过程执行 SQL UDF 的输出?
- google-sheets - 如何从另一个 Google 表格文档中导入前 7 天数据的平均值?
- firebase - 跳过使用 firebase init 托管创建拉取请求操作:github
- c# - 在 C3 powershell 中使用 ScriptBlock 和 WSManConnectionInfo
- python - 通过附加数据构建 Numpy 数组(事先不知道完整大小)
- windows - 如何使用 Powershell 列出包含字符串的文件的位置、文件名和行?
- asp.net-core - OpenIdConnect - 使用多个方案和 clientIds 时,状态验证似乎失败