You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Eloquent中定义关联产品的模型关系?

Laravel Eloquent 同表多对多关联定义

你的场景属于自关联的多对多关系——同一个product表中存储两种角色的记录(空调、过滤器),通过related_products中间表建立关联。不需要为中间表创建单独的Model,直接在Product模型中定义关联即可。

模型关联代码实现

在App\Models\Product中添加两个关联方法:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Product extends Model
{
    /**
     * 获取当前空调对应的所有过滤器
     */
    public function filters(): BelongsToMany
    {
        return $this->belongsToMany(
            self::class,
            'related_products',
            'product_id', // 中间表中指向当前模型(空调)的外键
            'filter_id'   // 中间表中指向关联模型(过滤器)的键
        );
    }

    /**
     * 获取当前过滤器对应的所有空调(可选,根据业务需求启用)
     */
    public function airConditioners(): BelongsToMany
    {
        return $this->belongsToMany(
            self::class,
            'related_products',
            'filter_id', // 中间表中指向当前模型(过滤器)的外键
            'product_id' // 中间表中指向关联模型(空调)的键
        );
    }
}

关联使用示例

  • 查询指定空调的所有过滤器:
// 获取ID为1的空调
$airConditioner = Product::find(1);
// 获取对应的过滤器集合
$filters = $airConditioner->filters;
  • 查询指定过滤器适配的所有空调:
// 获取ID为10的过滤器
$filter = Product::find(10);
// 获取适配的空调集合
$airConditioners = $filter->airConditioners;

内容的提问来源于stack exchange,提问作者Matthew Zarbatany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 18:32:52