与数据透视表中的fk有很多很多关系

时间:2018-05-01 22:11:16

标签: laravel laravel-5.5

我有以下结构:

数据库

成分
ID,
名称

产品
ID,
名称

ingredient_product
ingredient_id,
PRODUCT_ID,
ingredient_type_id

ingredient_types
ID,
名称

模型

产品型号

class Product extends Model
{
    public function ingredients() {
        return $this->belongsToMany(Ingredient::class)
            ->withPivot('ingredient_type_id');
    }
}

成分模型

class Ingredient extends Model
{
    public function products() {
        return $this->belongsToMany(Product::class)
            ->withPivot('ingredient_type_id');
    }
}

我的 SearchController

class SearchController extends Controller
{
    public function search(InitialSearchRequest $request)
    {
        $productsResults = Product::where('name', 'LIKE', '%' . $request['initial-search'] . '%')
            ->with('ingredients', 'brand')
            ->get();

        return view('search.index')
            ->with(compact('productsResults'))
            ->with('initial-search', $request['initial-search']);

    }
}

最后我的查看

<div class="card-group">
    @foreach($productsResults as $product)
        <div class="col-sm-6 col-md-4 col-lg-4">
            <div class="card"><img class="card-img-top" src="..." alt="Imagem do produto" style="width: 100%; height:100px; background-color: #696969;">
                <div class="card-body">
                    <h5 class="card-title">{{ $product->name }}</h5>
                    <p class="card-text">
                        Important Ingredients: <br>
                        @foreach($product->ingredients as $ingredient)
                            **{{ I need here the ingredient type }}** - {{ $ingredient->name }}
                        @endforeach
                    </p>
                </div>
            </div>
        </div>
    @endforeach
</div>

所以我需要在视图中显示我的产品,每种成分的成分和类型。

这种方法不起作用......

我需要帮助来完成这项任务。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用数据透视模型:

class IngredientProductPivot extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    public function ingredientType() {
        return $this->belongsTo(IngredientType::class);
    }
}

class Product extends Model
{
    public function ingredients() {
        return $this->belongsToMany(Ingredient::class)
            ->withPivot('ingredient_type_id')
            ->using(IngredientProductPivot::class);
    }
}

然后像这样访问:

{{ $ingredient->pivot->ingredientType->name }}

据我所知,没有办法急于加载type关系。

相关问题