gpt4 book ai didi

具有整数列的 Laravel 关系数组

转载 作者:行者123 更新时间:2023-12-02 21:14:51 25 4
gpt4 key购买 nike

类别表

enter image description here

产品表

enter image description here

我想与类别表创建关系 ->id 与产品表类别_id 建议对此关系有任何想法具有整数列关系的数组

Controller

Products::with('category')->get();

产品型号

public function category() {
return $this->hasMany(App\Models\Categories::class, 'id', 'category_id');
}

类别模型

public function product() {
return $this->belongsTo(Products::class,'category_id', 'id');
}

最佳答案

如果您希望它起作用,您应该创建多对多关系。

从数据库开始应该看起来像这样: enter image description here

这样您的产品和类别就会正确链接,如果您想向产品添加新类别,反之亦然,您只需将类别和产品的 ID 添加到category_product 表即可。

然后对于您的关系方法,在您的 Product.php(模型)中您将获得以下关系方法:

/**
* @return BelongsToMany
*/
public function categories(): BelongsToMany
{
return $this->belongsToMany(Category::class);
}

在您的 Category.php(模型)中:

/**
* @return BelongsToMany
*/
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class);
}

您现在可以使用以下方式获取产品的所有类别:

$product = Product::first();
$product->categories;

只是为了一些额外的信息。您可以使用您的模型来存储关系。

例如,您想向产品添加类别 1、2、3。

您可以简单地执行以下操作:

$product = Product::first();
$product->categories()->sync([1, 2, 3]);

关于具有整数列的 Laravel 关系数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com