How to use hasManyToMany in Phalcon


Feb '15

Apr '15

1

1582

0


Thien
32.6k
edited Mar '15
Feb '15

In Phalcon, relationships must be defined in the initialize() method of a model. The methods belongsTo(), hasOne(), hasMany() and hasManyToMany() define the relationship between one or more fields from the current model to fields in another mode

I will demo relationship hasManyToMany, We need to create 3 table:

Table one I call name Posts

    class Posts extends ModelBase
    {

    const POST_QUESTIONS = 'questions';
    const POST_TIPS      = 'tips';
    /**
     *
     * @var integer
     */
    protected $id;

    /**
     *
     * @var integer
     */
    protected $tagsId;

    [...]
    public function initialize()
    {
        $this->hasManyToMany(
            'id',
            __NAMESPACE__ . '\PostsTags',
            'postsId',
            'tagsId',
            __NAMESPACE__ . '\Tags',
            'id',
            ['alias' => 'tag']
        );
    }

Table two I call Tags:

class Tags extends ModelBase
{

    /**
     *
     * @var integer
     */
    protected $id;

    /**
     *
     * @var string
     */
    protected $name;

    [...]
    public function initialize()
    {
        $this->useDynamicUpdate(true);
        $this->hasManyToMany(
            'id',
            __NAMESPACE__ . '\PostsTags',
            'PostsId',
            'TagsId',
            __NAMESPACE__ . '\Posts',
            'id',
            array('alias' => 'post')
        );
    }

Table three I call PostsTags:

class PostsTags extends ModelBase
{

    /**
     *
     * @var integer
     */
    protected $id;

    /**
     *
     * @var integer
     */
    protected $postsId;

    /**
     *
     * @var integer
     */
    protected $tagsId;

    [...]
    public function initialize()
    {
        $this->belongsTo('postsId', __NAMESPACE__ .'/Posts', 'id', ['alias' => 'post']);
        $this->belongsTo('tagsId',  __NAMESPACE__ .'/Tags',  'id', ['alias' => 'tag']);
    }

Then We use it, In controller we create a action name indexAction

class QuestionsController extends ControllerBase
{
    public function indexAction()
    {
        / Pass the posts data to the view
        $this->view->posts = new Posts:find();
    }
}

Then In view we just call it

{% if posts|length %}
<div class="container">
    <br/>
{% for post in posts %}
    <h3> post.getTitle()</h3>
    <p>
    //get all tags a post
    {% for tag in post.getTag() %}
        <span class="label bg-primary">
            #{{ tag.getName() }}
        </span>
                &nbsp;
     {% endfor %}
    </p>
{% endfor%}
{% endif %}

Do you like post ?


naaness
128

Yes!!, It was easy!