Home > other >  How to fetch class / build own ORM?
How to fetch class / build own ORM?

Time:02-10

Let say, I have 2 Objects / Model

class ProductModel
{
    private int    $productid;
    private string $name;
    private string $description;
    private float  $price;
    private string $imagepath;

class CartModel
{
    private int $quantity;
    private int $totalprice;
    private int $ordered;
}

And my repository goes like this

    /**
     * Get Cart Items from unique (id) customer
     *
     * @param int $customerId
     * @return bool|array
     */
    public function getCartItems(int $customerId): bool|array
    {
        $tableName = $this->setTableName();
        $className = $this->setClassName();
        $statement = $this->connection->prepare("SELECT cart.quantity, product.productid, product.name, product.imagepath, product.price FROM `$tableName` as cart LEFT JOIN product as product ON product.productid = cart.product_id WHERE cart.customer_id=:customerId AND cart.ordered=0;");
        $statement->execute(['customerId' => $customerId]);
        return $statement->fetchAll(PDO::FETCH_CLASS, $className);
    }

My task is literally to build ORP without any framework. So far, I have fetched everything inside ProductModel.php, but some data are joined (like you can see above), and they come from 2 different tables, so it doesn't make any sense, because they are 2 separated models. How can I archive, to store data that comes from cart to cart model, and data that comes from products to product model, without loosing their join / relationship? Thanks for help!

CodePudding user response:

  •  Tags:  
  • Related