C
C
cadaver2016-10-21 22:58:54
MySQL
cadaver, 2016-10-21 22:58:54

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:

  • Products 1: Category 3 (Cat3), Category 5 (Cat5)
  • Products 2: Category 1 (Cat1), Category 2 (Cat2)

etc
@foreach($products as $product)
{{$product->name}}: <тут категории этой продукции и ее слаги>
@endforeach

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Rudkovsky, 2016-10-22
@aleshka-ne-programmist

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) {
    // Делаете что хотите с категориями этого товара
}

You can do the same with categories:
$category = App\Category::find(1); // Поулчаем запись с id = 1
foreach ($category->products as $product) {
    // Продукты в категории
}

Adding an entry to a category:
$product = ...;
$category = App\Category::find(1); // Для примера будем использовать категорию с id = 1
$category->products()->attach($product->id);

Or add multiple entries at once:
$category = App\Category::find(1); // Для примера будем использовать категорию с id = 1
$category->products()->attach([1, 2, 3]); // Добавляем товары с id = 1, 2, 3 в категорию с id = 1

Removing products from a category:
$category = App\Category::find(1); // Для примера будем использовать категорию с id = 1
$category->products()->detach(1); // Удаляем продукт с id = 1 из категории с id = 1. Так же можно передать массив для удаления сразу нескольких продуктов из категории

Everything described above works in both directions, i.e. you can add and remove categories to the product in the same way (similarly to each of the examples, see the first and second examples)

E
entermix, 2016-10-21
@entermix

If normal, you should have the following tables:

categories
id, name, ...

products...
id, name...

categories_products
category_id, product_id

There should be a connection has many throughand then you already do:
foreach($product->categories as $category)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question