具有整数列的Laravel关系数组

类别表

具有整数列的Laravel关系数组

产品表

具有整数列的Laravel关系数组

我想与类别表建立关系->与产品表category_id关联的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');
}
x4536453 回答:具有整数列的Laravel关系数组

如果您希望此方法有效,则应建立多对多关系。

启动数据库应如下所示: 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]);
,

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

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')
    ]);
}
本文链接:https://www.f2er.com/3161766.html

大家都在问