【问题标题】:Is there any way of making a model Relationship with an array of ids有没有办法用一组 id 建立模型关系
【发布时间】:2022-01-13 13:10:08
【问题描述】:

有谁知道如何建立外键是一组 id 而不是一个 ID 的关系?

样品控制器:

$products = Products::with('productCategory')->get();

模型关系:

public function productCategory()
{
    return $this->belongsTo(productCategory::class, 'product_category_id', 'id');
}

产品表:

[
    {
        'id': 1,
        'name': 'Mango',
        'product_category_id': ['1', '2']
    }
]

产品类别表:

[
    {
        'id': 1,
        'name': 'Food'
    },
    {
        'id': 2,
        'name': 'Fruits'
    }
]

【问题讨论】:

  • 有没有可能,是的,你应该这样做,不,你真的不应该

标签: laravel eloquent model relationship


【解决方案1】:

没有。从 MySQL 的角度来看,它是行不通的。如果存在外键关系,则本地键(即 products 表上的 product_category_id)必须在各个方面与外键(即 product_categories 表上的 id)完全匹配。您不能将数组与整数匹配。

如果您需要一个模型的实例与不同模型的许多不同实例相关联,那么您不需要重新发明轮子,您可以使用 Laravel 的多对多关系 (https://laravel.com/docs/8.x/eloquent-relationships#many-to-many) 因为,想必一个产品可以有多个分类,一个分类可以有多个产品。

【讨论】:

    猜你喜欢
    • 2013-06-03
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2022-06-17
    相关资源
    最近更新 更多