Answer the question
In order to leave comments, you need to log in
Laravel - how to display data from one table based on the second?
There is a table with categories (id, name, slug):
1 - Category 1 - Cat1
2 - Category 2 - Cat2
3 - Category 3 - Cat3
There is a table with products (id, name, cat_id)
1 - Post 1 - 2.6, 8
2- Post 2 - 1.2
3- Post 3 - 4.7
Each product has category IDs separated by commas. those. cat_id=2,6,8
When displaying all product values, how can I also display the assigned categories?
those. I want to get a list as output:
@foreach($products as $product)
{{$product->name}}: <тут категории этой продукции и ее слаги>
@endforeach
Answer the question
In order to leave comments, you need to log in
Example:
https://gist.github.com/AlexeyRudkovskiy/9fb4fcfd3...
At the beginning of each file, the path where it is located is indicated in the comment.
Next, write like this:
$product = App\Product::find(1); // Поулчаем запись с id = 1
foreach ($product->categories as $category) {
// Делаете что хотите с категориями этого товара
}
$category = App\Category::find(1); // Поулчаем запись с id = 1
foreach ($category->products as $product) {
// Продукты в категории
}
$product = ...;
$category = App\Category::find(1); // Для примера будем использовать категорию с id = 1
$category->products()->attach($product->id);
$category = App\Category::find(1); // Для примера будем использовать категорию с id = 1
$category->products()->attach([1, 2, 3]); // Добавляем товары с id = 1, 2, 3 в категорию с id = 1
$category = App\Category::find(1); // Для примера будем использовать категорию с id = 1
$category->products()->detach(1); // Удаляем продукт с id = 1 из категории с id = 1. Так же можно передать массив для удаления сразу нескольких продуктов из категории
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question