Question

http://docs.phalconphp.com/en/0.6.0/reference/phql.html

Usage Example

To better explain how PHQL works consider the following example. We have two models “Cars” and “Brands”:

<?php
    class Cars extends Phalcon\Mvc\Model
    {
        public $id;

        public $name;

        public $brand_id;

        public $price;

        public $year;

        public $style;

        /**
        * This model is mapped to the table sample_cars
        */
        public function getSource()
        {
            return 'sample_cars';
        }

        /**
         * A car only has a Brand, but a Brand have many Cars
         */
        public function initialize()
        {
            $this->belongsTo('brand_id', 'Brands', 'id');
        }
    }

And every Car has a Brand, so a Brand has many Cars:

<?php
    class Brands extends Phalcon\Mvc\Model
    {
        public $id;

        public $name;

        /**
         * The model Brands is mapped to the "sample_brands" table
         */
        public function getSource()
        {
            return 'sample_brands';
        }

        /**
         * A Brand can have many Cars
         */
        public function initialize()
        {
            $this->hasMany('id', 'Brands', 'brand_id'); // here
        }
    }
Was it helpful?

Solution

You are correct. The relationship should have been hasMany on Cars not Brands. The corrected example is below

http://docs.phalconphp.com/en/latest/reference/phql.html

<?php

class Cars extends Phalcon\Mvc\Model
{
    public $id;

    public $name;

    public $brand_id;

    public $price;

    public $year;

    public $style;

   /**
    * This model is mapped to the table sample_cars
    */
    public function getSource()
    {
        return 'sample_cars';
    }

    /**
     * A car only has a Brand, but a Brand have many Cars
     */
    public function initialize()
    {
        $this->belongsTo('brand_id', 'Brands', 'id');
    }
}

And every Car has a Brand, so a Brand has many Cars:

<?php

class Brands extends Phalcon\Mvc\Model
{

    public $id;

    public $name;

    /**
     * The model Brands is mapped to the "sample_brands" table
     */
    public function getSource()
    {
        return 'sample_brands';
    }

    /**
     * A Brand can have many Cars
     */
    public function initialize()
    {
        $this->hasMany('id', 'Cars', 'brand_id');
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top