H
H
HabrDima202020-11-26 22:27:50
Laravel
HabrDima20, 2020-11-26 22:27:50

How to make a selection from the product database?

There is a code by which I sort the goods with the hasMany connection .

$vendor = $request->vendor;
        
        $products = Product::with('user')
            ->when($vendor, function ($query, $vendor) {
                    $query->where('vendor_id', $vendor);
            })
            ->paginate(15);

But there is also a Many-to-Many connection, and if you pass an array, it doesn't work!
And you need to sort by size and color, and one product may have more than one size and color!
I need to sort by the id array, but I don’t understand how to do it right?
->when($size, function ($query, $size) {
               $query->where('size_id', $size);   //----эта строка не правильна потому что
                                                                   //  у меня  id  в  промежуточной  таблице 
          })


Table example

мне нужно примерно так
таблица товары
$products = [
    'item_1' => [
        'id' => 1,
        'name' => 'product_1',
        'size' => 'S'
    ],
    'item_2' => [
        'id' => 2,
        'name' => 'product_2',
        'size' => 'XL',
    ],
    'item_3' => [
        'id' => 3,
        'name' => 'product_3',
        'size' => 'S',
    ],
    'item_4' => [
        'id' => 3,
        'name' => 'product_5',
        'size' => 'L',
    ],
];


таблица размеры
$sizes = [
    'size' => [
        'id' => 1,
        'name' => 'S',
    ],
    'size_2' => [
        'id' => 2,
        'name' => 'L',
    ],
    'size_3' => [
        'id' => 3,
        'name' => 'XL',
    ],

];


$prosuct_size = [
    'id' => [
        'product_id' => 1,
        'size_id' => 1,
    ],
'id' => [
        'product_id' => 3,
        'size_id' => 1,
    ],
'id' => [
        'product_id' => 4,
        'size_id' => 2,
    ],

]


это примерно
сделаны checkbox из которых приходят id.
<div class="size">
    <input type="checkbox" name="size" value="size[i][id]">
    <button>click</button>
</div>

Как можно если выбрать например два или три checkbox, вывести товар который принадлежит этому размеру????

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
the5x, 2020-11-29
@the5x

You can do orderBy directly in the model where you have a belongsTo()->orderBy() relationship

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question