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

How to select all columns of a Many to Many relationship model

I have a 3 models/tables:

Articles (id, title, content)

Categories(id, name, parent_id),

AriclesHasCategories(articlesId, categories Id)

I did all the relationships, and it work good when I do a simple findFirst, or find.

but it doesn't work when I for example Articles::find('category.name = 'Movies')

but I don't know how I can do to filter my articles results with e.g(WHERE categoryName = 'Programming')

Should I only use PHQL for that so I do a normal SQL query, I mean the ORM don't manage conditions like that ?



51.2k

This is what I do. But i use category_slug from a category_translation table, instead of category name:

    public static function findByCategorySlug($categorySlug, $itemsPerPage = 10, $currentPage = 1, $limit = 100)
    {
        $ct = CategoryTranslation::findFirst(array(
            "slug = :slug:",
            "bind" => array(
                "slug" => $categorySlug
            )
        ));

        if (!$ct) {
            throw new \Exception(ErrorCode::ERR_OBJECT_NOT_FOUND, 404);
        }

        $result = $ct
        ->getCategory(array("is_active = 1"))
        ->getPosts(array(
            "is_active = 1",
            "order" => "created_at DESC",
            "limit" => $limit > 0 && $limit <= 100 ? $limit : 100
        ))
        ->filter(function($post){
            return $post->toArray();
        });

        $paginator = new \Phalcon\Paginator\Adapter\NativeArray(
            array(
                "data" => $result,
                "limit"=> $itemsPerPage,
                "page" => $currentPage
            )
        );

        return $paginator->getPaginate();
    }