【发布时间】:2020-02-02 11:11:26
【问题描述】:
更新:这里提到的问题是由 XAMPP 使用 MariaDB 而不是 MySQL 引起的。我已按照here 的答案将其切换到 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');
}
}
控制器
以下是控制器sn-p。
产品控制器
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
【问题讨论】:
-
更改此
withPivot('product_id ','special_offer_id ' ); -
@ZainFarooq 还是一样 :-(
-
试试这个
$this->belongsToMany(SpecialOffer::class, 'product_special_offer');和$this->belongsToMany(Product::class, 'product_special_offer'); -
@ZainFarooq 我之前尝试指定表名,在你提到之后现在也做了同样的事情。还是一样。
-
MySQL 和 MariaDB 是可以互换的,将一个换成另一个不会改变任何事情,尤其是对于像您正在运行的查询这样非常基本的查询。
标签: php mysql laravel eloquent