从产品颜色表中获取颜色ID,但如何从颜色表中获取颜色名称

时间:2020-02-04 08:45:05

标签: php laravel eloquent

$product = Products::where('product_slug', $slug)->first();
$productcolours = Productcolour::all()->where('product_id', $product->id);
$colour = Colour::all();

product.blade

@foreach($productcolours as $productcolour)
{{$productcolour->color_id}}
@endforeach

获取颜色名称

2 个答案:

答案 0 :(得分:0)

您应该能够在ProductsColour之间建立belongsToMany关系,例如将以下内容添加到您的Products模型中(如果尚不存在):

public function colors()
{
    return $this->belongsToMany(Color::class);
}

在没有看到您的表定义的情况下,我无法肯定地说上面的代码将按原样工作。当前假设您已遵循Laravel的标准命名约定。

那么您应该只需能够加载关系:

$product = Products::with('colors')->where('product_slug', $slug)->first();
@foreach($product->colors as $color)
    {{ $color->name }}
@endforeach

仅供参考,以后我建议使用数据库进行过滤,而不是检索所有记录的所有,然后将其过滤掉,即

此:

$productcolours = Productcolour::all()->where('product_id', $product->id);

将成为:

$productcolours = Productcolour::where('product_id', $product->id)->get();

答案 1 :(得分:0)

将以下代码添加到您的产品模型中

public function color()
{
    return $this->hasOne('App\Productcolour', 'id', 'color_id');
}

当您的产品表color_id与颜色表id匹配时,以上代码将起作用

要在前端使用下面的代码(1是产品ID,请使用动态ID $product->id

{{Products::find(1)->color}}

或 在控制器$colour = Products::find(1)->color;