Laravel 包含整数列的关系数组

Laravel Relationship Array with integer column

类别Table

产品Table

我想与类别 tables ->id 与产品建立关系 table category_id 提出关于此关系的任何想法 具有整数列关系的数组

控制器

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');
}

如果你想让这个工作,你应该创建一个多对多的关系。

开始你的数据库应该是这样的:

这样您的产品和类别就会正确链接,如果您想向产品添加新类别或相反,您只需将类别和产品的 ID 添加到 category_product table.

然后对于你的关系方法,在你的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]);

这似乎是一个很好的数据透视表 table,但如果出于某种原因您确实需要此架构,那么也许您可以使用子查询。

Products::addSelect(['category' => Category::select('name')
    ->whereIn('id', 'destinations.category_id')
])->get();

您必须查看您的 laravel 版本是否提供此功能。 https://github.com/laravel/framework/pull/29567

如果您想将其作为模型的一部分,可以将其添加为范围。

public function scopeWithCategories($query) 
{
    $query->addSelect(['category' => Category::select('name')
        ->whereIn('id', 'destinations.category_id')
    ]);
}