у меня следующая структура:
ингредиенты
id,
название
продукты
id,
название
ингредиент_продукт
ингредиент_id,
product_id,
ингредиент_типа_ид
ингредиенты_типы
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>
Поэтому мне нужно показать в обзоре свои продукты с ингредиентами и типом каждого ингредиента.
Этот подход не работает ......
Мне нужна помощь, чтобы закончить эту задачу.
Спасибо за любую помощь.
Вы можете использовать сводную модель:
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
.