We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Fetch some of columns to another model class.

Hi, I'm working with phalcon for about two weeks now and i have some question about Models.

So, for example I have two tables: products and categories

CREATE TABLE IF NOT EXISTS "products"
(
  "id"          SERIAL        NOT NULL,
  "title"       VARCHAR(512)  NOT NULL,
  "category_id" INT           DEFAULT NULL,

  PRIMARY KEY ("id")
) Without Oids;

CREATE TABLE IF NOT EXISTS "categories"
(
  "id"          SERIAL        NOT NULL,
  "title"       VARCHAR(512)  NOT NULL,

  PRIMARY KEY ("id")
) Without Oids;

My goal is to fetch all data I need at once with one query. I create view "getProducts"

CREATE OR REPLACE VIEW "getProducts" AS SELECT
    products.id,
    products.title,
    products.category_id,
    category.id as "category.id"
    category.title as "category.title"
FROM products
LEFT JOIN categores as category ON categories.id = products.category_id

The problem is I cannot figure out how to fetch category.id and category.title to separate model. As I understand, fetching data to specific class takes place in Resultset class. How can i replace Resultset with my own class? Or there is another way to fetch some of the columns to separate model? Or another way to fetch data at once?

I will be very grateful for the help.

P.s. sorry for my english )



125.8k
Accepted
answer

So from your query you want to put all the "products" columns in a Product model, and all the "category" columns in a Category model? That can't be done automatically with Phalcon't built-in ORM. What you can do is just run that query manually, create new Product and Category objects, then manually transfer the data from your result into the objects.

P.S - your English is just fine - better than some native English speakers on here.



1.7k

Thanks for answer.