October CMS 3.x中Product与Category双关联配置问题求助
October CMS 3.x 实现分类独立指定最多3个展示产品
1. 创建多对多中间表
首先需要创建独立的中间表category_showcase_products,用于存储分类和展示产品的关联关系,避免影响产品的归属分类:
CREATE TABLE `category_showcase_products` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `category_id` INT UNSIGNED NOT NULL, `product_id` INT UNSIGNED NOT NULL, `sort_order` INT UNSIGNED DEFAULT 0, -- 可选,用于控制展示顺序 UNIQUE KEY `category_product_unique` (`category_id`, `product_id`), FOREIGN KEY (`category_id`) REFERENCES `categories`(`id`) ON DELETE CASCADE, FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE CASCADE );
唯一索引可以防止同一个分类重复选择同一个产品,sort_order字段可用于自定义展示产品的排序顺序。
2. 配置模型关联
Category 模型
修改Category.php,新增多对多关联showcases,与已有的products(归属产品关联)区分开:
namespace YourNamespace\Models; use Model; class Category extends Model { // 已有的归属产品关联(不变) public $hasMany = [ 'products' => Product::class ]; // 新增的展示产品多对多关联 public $belongsToMany = [ 'showcases' => [ Product::class, 'table' => 'category_showcase_products', // 指定中间表 'key' => 'category_id', 'otherKey' => 'product_id', 'pivot' => ['sort_order'], // 若使用排序字段,需在此声明 'orderBy' => 'sort_order' // 按排序字段排序展示产品 ] ]; }
Product 模型(可选)
如果需要在产品后台查看该产品被哪些分类选为展示产品,可添加反向关联:
namespace YourNamespace\Models; use Model; class Product extends Model { // 已有的归属分类关联(不变) public $belongsTo = [ 'category' => Category::class ]; // 新增的反向展示关联 public $belongsToMany = [ 'showcased_in' => [ Category::class, 'table' => 'category_showcase_products', 'key' => 'product_id', 'otherKey' => 'category_id' ] ]; }
3. 配置分类后台字段表单
修改category/fields.yaml,添加showcases字段,设置选择限制和关联规则:
fields: # 其他已有字段... showcases: label: 展示产品 type: relation nameFrom: name # 替换为你的Product模型中用于显示的字段(如产品名称/标题) description: 最多选择3个产品作为分类页展示 relation: showcases # 对应Category模型中的关联名称 maxItems: 3 # 限制最多选择3个 span: full # 可选:若需要排除当前分类的产品,可添加scope # scope: filterNotInCurrentCategory
如果需要排除当前分类的产品,在Product模型中添加查询作用域:
public function scopeFilterNotInCurrentCategory($query, $category) { return $query->where('category_id', '!=', $category->id); }
4. 功能验证
进入后台编辑分类时,选择展示产品将不会修改产品的归属分类(category_id字段),仅在中间表中存储关联关系。在前端分类页面中,可通过$category->showcases直接获取选中的展示产品列表。
内容的提问来源于stack exchange,提问作者Edvinas
相关产品推荐
相关产品推荐

