Files
web_work/app/Models/Cart.php
kirill.khorkov d2c15ec37f [MVC] Полная миграция на MVC архитектуру
- Создано ядро MVC: App, Router, Controller, Model, View, Database
- Созданы модели: User, Product, Category, Cart, Order
- Созданы контроллеры: Home, Auth, Product, Cart, Order, Page, Admin
- Созданы layouts и partials для представлений
- Добавлены все views для страниц
- Настроена маршрутизация с чистыми URL
- Обновлена конфигурация Docker и Apache для mod_rewrite
- Добавлена единая точка входа public/index.php
2026-01-03 11:48:14 +03:00

146 lines
4.3 KiB
PHP

<?php
namespace App\Models;
use App\Core\Model;
/**
* Cart - модель корзины
*/
class Cart extends Model
{
protected string $table = 'cart';
protected string $primaryKey = 'cart_id';
/**
* Получить корзину пользователя
*/
public function getUserCart(int $userId): array
{
$sql = "SELECT
c.cart_id,
c.product_id,
c.quantity,
p.name,
p.price,
p.image_url,
p.stock_quantity,
p.is_available
FROM {$this->table} c
JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ? AND p.is_available = TRUE
ORDER BY c.created_at DESC";
return $this->query($sql, [$userId]);
}
/**
* Получить общую сумму корзины
*/
public function getCartTotal(int $userId): array
{
$sql = "SELECT
SUM(c.quantity) as total_quantity,
SUM(c.quantity * p.price) as total_amount
FROM {$this->table} c
JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ? AND p.is_available = TRUE";
$result = $this->queryOne($sql, [$userId]);
return [
'quantity' => (int) ($result['total_quantity'] ?? 0),
'amount' => (float) ($result['total_amount'] ?? 0)
];
}
/**
* Получить количество товаров в корзине
*/
public function getCount(int $userId): int
{
$sql = "SELECT COALESCE(SUM(quantity), 0) as total FROM {$this->table} WHERE user_id = ?";
$result = $this->queryOne($sql, [$userId]);
return (int) $result['total'];
}
/**
* Добавить товар в корзину
*/
public function addItem(int $userId, int $productId, int $quantity = 1): bool
{
// Проверяем, есть ли уже этот товар в корзине
$existing = $this->findWhere([
'user_id' => $userId,
'product_id' => $productId
]);
if ($existing) {
// Увеличиваем количество
$newQuantity = $existing['quantity'] + $quantity;
return $this->update($existing['cart_id'], [
'quantity' => $newQuantity,
'updated_at' => date('Y-m-d H:i:s')
]);
}
// Добавляем новую запись
return $this->create([
'user_id' => $userId,
'product_id' => $productId,
'quantity' => $quantity
]) !== null;
}
/**
* Обновить количество товара в корзине
*/
public function updateQuantity(int $userId, int $productId, int $quantity): bool
{
$sql = "UPDATE {$this->table}
SET quantity = ?, updated_at = CURRENT_TIMESTAMP
WHERE user_id = ? AND product_id = ?";
return $this->execute($sql, [$quantity, $userId, $productId]);
}
/**
* Удалить товар из корзины
*/
public function removeItem(int $userId, int $productId): bool
{
$sql = "DELETE FROM {$this->table} WHERE user_id = ? AND product_id = ?";
return $this->execute($sql, [$userId, $productId]);
}
/**
* Очистить корзину пользователя
*/
public function clearCart(int $userId): bool
{
$sql = "DELETE FROM {$this->table} WHERE user_id = ?";
return $this->execute($sql, [$userId]);
}
/**
* Проверить, есть ли товар в корзине
*/
public function hasItem(int $userId, int $productId): bool
{
$item = $this->findWhere([
'user_id' => $userId,
'product_id' => $productId
]);
return $item !== null;
}
/**
* Получить товар из корзины
*/
public function getItem(int $userId, int $productId): ?array
{
return $this->findWhere([
'user_id' => $userId,
'product_id' => $productId
]);
}
}