Работа с БД

niko42

Новичок
Доброго дня!

Есть две таблицы:

PHP:
CREATE TABLE IF NOT EXISTS `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `article` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `brand_id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(500) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `price` int(11) DEFAULT NULL,
  `old_price` int(11) DEFAULT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `params` text COLLATE utf8_unicode_ci NOT NULL,
  `like` int(11) NOT NULL DEFAULT '1',
  `visible` tinyint(1) NOT NULL DEFAULT '1',
  `in_stock` tinyint(1) NOT NULL DEFAULT '0',
  `meta_title` varchar(500) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `meta_keywords` varchar(500) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `meta_description` varchar(500) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `url` (`url`),
  UNIQUE KEY `article` (`article`),
  FULLTEXT KEY `name` (`name`,`article`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=171 ;

CREATE TABLE IF NOT EXISTS `product_image` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `img` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `position` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`img`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=367 ;
Есть ли возможность, как-то связать эти таблицы в БД не используя JOIN и получить такой результат: (в независимости от запроса SELET `product` или `product_image`)
PHP:
application\lib\Product Object
        (
            [id] =>
            [url] =>
            [article] =>
            [brand_id] =>
            [name] =>
            [price] =>
            [old_price] =>
            [description] =>
            [params] =>
            [like] =>
            [visible] =>
            [in_stock] =>
            [meta_title] =>
            [meta_keywords] =>
            [meta_description] =>
            [_image:protected] => Array
                (
                    [0] => application\lib\Product_Image Object
                        (
                            [id] =>
                            [product_id] =>
                            [img] =>
                            [position] =>
                        )

                )

        )
 

c0dex

web.dev 2002-...
Команда форума
Партнер клуба
ORM, ибо простым запросом ты не получишь такой результат. Сделать просто на каждую сужность из product подзапрос к product_image
 

niko42

Новичок
ORM, ибо простым запросом ты не получишь такой результат. Сделать просто на каждую сужность из product подзапрос к product_image
Спасибо в данный момент у меня так:
PHP:
namespace application\lib;
class Product_Image {

    public $id, $product_id, $img, $position;

    function __construct(){}

    /**
    * @param int $id
    */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
    * @return int
    */
    public function getId()
    {
        return $this->id;
    }

    /**
    * @param string $name
    */
    public function setImg($name)
    {
        $this->img = $name;
    }

    /**
    * @return string
    */
    public function getImg()
    {
        return $this->img;
    }

    /**
    * @param int $position
    */
    public function setPosition($position)
    {
        $this->position = $position;
    }

    /**
    * @return int
    */
    public function getPosition()
    {
        return $this->position;
    }

    /**
    * @param int $product_id
    */
    public function setProductId($product_id)
    {
        $this->product_id = $product_id;
    }

    /**
    * @return int
    */
    public function getProductId()
    {
        return $this->product_id;
    }

}
PHP:
namespace application\lib;

use application\modal\Product_Image as ModalProductImage;

class Product{

    public  $id, $url, $article, $brand_id, $name, $price, $old_price, $description, $params, $like, $visible, $in_stock, $meta_title, $meta_keywords, $meta_description;
    protected $_image;

    function __construct(){}

    /**
    * @param Product_Image $image
    */
    public function setImage($image)
    {
        $this->_image = $image;
    }

    /**
    * @return array(Product_Image)
    */
    public function getImage()
    {
        if(!isset($this->_image)){
            $arr = ModalProductImage::get($this->id);
            if(empty($arr))
                $this->_image = array(new Product_Image());
            else
                $this->_image = ModalProductImage::get($this->id);
        }

        return $this->_image;
    }

    /**
    * @return Product_Image
    */
    public function getFirstImage(){
        if(is_array($this->getImage())){
            return array_shift($this->getImage());
        }

        return $this->getImage();
    }

    /**
    * @return Product_Image
    */
    public function getLastImage(){
        if(is_array($this->getImage()))
            return array_pop($this->getImage());
        return $this->getImage();
    }

    /**
    * @param string $article
    */
    public function setArticle($article)
    {
        $this->article = $article;
    }

    /**
    * @return string
    */
    public function getArticle()
    {
        return $this->article;
    }

    /**
    * @param int $brand_id
    */
    public function setBrandId($brand_id)
    {
        $this->brand_id = $brand_id;
    }

    /**
    * @return int
    */
    public function getBrandId()
    {
        return $this->brand_id;
    }

    /**
    * @param string $description
    */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
    * @return string
    */
    public function getDescription()
    {
        return $this->description;
    }

    /**
    * @param int $id
    */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
    * @return int
    */
    public function getId()
    {
        return $this->id;
    }

    /**
    * @param int $in_stock
    */
    public function setInStock($in_stock)
    {
        $this->in_stock = $in_stock;
    }

    /**
    * @return int
    */
    public function getInStock()
    {
        return $this->in_stock;
    }

    /**
    * @param int $like
    */
    public function setLike($like)
    {
        $this->like = $like;
    }

    /**
    * @return int
    */
    public function getLike()
    {
        return $this->like;
    }

    /**
    * @param string $meta_description
    */
    public function setMetaDescription($meta_description)
    {
        $this->meta_description = $meta_description;
    }

    /**
    * @return string
    */
    public function getMetaDescription()
    {
        return $this->meta_description;
    }

    /**
    * @param string $meta_keywords
    */
    public function setMetaKeywords($meta_keywords)
    {
        $this->meta_keywords = $meta_keywords;
    }

    /**
    * @return string
    */
    public function getMetaKeywords()
    {
        return $this->meta_keywords;
    }

    /**
    * @param string $meta_title
    */
    public function setMetaTitle($meta_title)
    {
        $this->meta_title = $meta_title;
    }

    /**
    * @return string
    */
    public function getMetaTitle()
    {
        return $this->meta_title;
    }

    /**
    * @param string $name
    */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
    * @return string
    */
    public function getName()
    {
        return $this->name;
    }

    /**
    * @param int $old_price
    */
    public function setOldPrice($old_price)
    {
        $this->old_price = $old_price;
    }

    /**
    * @return int
    */
    public function getOldPrice()
    {
        return $this->old_price;
    }

    /**
    * @param int $price
    */
    public function setPrice($price)
    {
        $this->price = $price;
    }

    /**
    * @return int
    */
    public function getPrice()
    {
        return $this->price;
    }


    /**
    * @param string $params
    */
    public function setParams($params)
    {
        $this->params = $params;
    }

    /**
    * @return string
    */
    public function getParams()
    {
        return $this->params;
    }

    /**
    * @param string $url
    */
    public function setUrl($url)
    {
        $this->url = $url;
    }

    /**
    * @return string
    */
    public function getUrl()
    {
        return $this->url;
    }

    /**
    * @param int $visible
    */
    public function setVisible($visible)
    {
        $this->visible = $visible;
    }

    /**
    * @return int
    */
    public function getVisible()
    {
        return $this->visible;
    }

}
 

niko42

Новичок
ORM, ибо простым запросом ты не получишь такой результат. Сделать просто на каждую сужность из product подзапрос к product_image
А не подскажите, ORM это как ?

P.S. ведь в ORM, в запросе придется использовать JOIN
 
Последнее редактирование:

c0dex

web.dev 2002-...
Команда форума
Партнер клуба
ORM это в гугле ищется, находится и читается, например, тут - https://ru.wikipedia.org/wiki/ORM

У меня масса вопросов по коду, наример, нафига делать паблик свойства в классе, если у вас там на все геттеры и сеттеры есть?
 

niko42

Новичок
ORM это в гугле ищется, находится и читается, например, тут - https://ru.wikipedia.org/wiki/ORM

У меня масса вопросов по коду, наример, нафига делать паблик свойства в классе, если у вас там на все геттеры и сеттеры есть?
Вообще у меня все protected стоит) Добавляя на форум изменил
 

c0dex

web.dev 2002-...
Команда форума
Партнер клуба
niko42, тот, кто это посоветовал видимо болен, чуть более, чем полностью. Либо советовал он не в том свете, в котором об этом писал я. В целом же, я не вижу проблемы сделать так как тебе надо, только про "в независимости от типа запроса" я не совсем понял, в первой редакции поста этого не было вроде)
 
  • Like
Реакции: WMix

niko42

Новичок
Т.е. смотрите:
Мы берем продукт из БД
PHP:
/**
    * @param $id
    * @return \application\lib\Product
    */
    public static function get($id){
        $db = DB::getInstancePDO()->prepareQuery(
            "SELECT * FROM `product` WHERE `id` = ?",
            array($id)
        );

        if($db->rowCount() == 0)
            return new \application\lib\Product();

        return $db->fetchObject('\application\lib\Product');
    }
Получаем результат:
PHP:
application\lib\Product Object
        (
            [id] =>
            [url] =>
            [article] =>
            [brand_id] =>
            [name] =>
            [price] =>
            [old_price] =>
            [description] =>
            [params] =>
            [like] =>
            [visible] =>
            [in_stock] =>
            [meta_title] =>
            [meta_keywords] =>
            [meta_description] =>
        )
Окей.

Но я хочу получить результат:
PHP:
application\lib\Product Object
        (
            [id] =>
            [url] =>
            [article] =>
            [brand_id] =>
            [name] =>
            [price] =>
            [old_price] =>
            [description] =>
            [params] =>
            [like] =>
            [visible] =>
            [in_stock] =>
            [meta_title] =>
            [meta_keywords] =>
            [meta_description] =>
            [_image:protected] => Array
                (
                    [0] => application\lib\Product_Image Object
                        (
                            [id] =>
                            [product_id] =>
                            [img] =>
                            [position] =>
                        )

                )

        )
 

c0dex

web.dev 2002-...
Команда форума
Партнер клуба
Есть вариант с ленивой подгрузкой изображения, либо напямую, допилить метод get в продукте.
 

niko42

Новичок
Есть вариант с ленивой подгрузкой изображения, либо напямую, допилить метод get в продукте.
дык и так:
PHP:
/**
    * @return array(Product_Image)
    */
    public function getImage()
    {
        if(!isset($this->_image)){
            $this->_image = ModalProductImage::get($this->id);
        }

        return $this->_image;
    }
А так не интересно)))
 
Последнее редактирование:

c0dex

web.dev 2002-...
Команда форума
Партнер клуба
niko42, дык а что ты хочешь? Главное правило - чтобы работало стабильно)))
 

Вурдалак

Продвинутый новичок
niko42, в общем случае это не очень тривиальная штука, hydration/deserialization. Посмотри реализацию в какой-нибудь Doctrine.

А для автоматический ленивой загрузки (читай: «без JOIN») потребуется, чтобы ORM делала proxy-класс для Image.
 
Сверху