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

Storing Related Records when using multiple modules (using namespaces)

In: https://docs.phalcon.io/en/latest/reference/models.html#storing-related-records

<?php

// Create an artist
$artist          = new Artists();
$artist->name    = 'Shinichi Osawa';
$artist->country = 'Japan';

// Create an album
$album         = new Albums();
$album->name   = 'The One';
$album->artist = $artist; // Assign the artist
$album->year   = 2008;

// Save both records
$album->save();

But when you have multiple modules and newArtists() is a new \Common\Models\Artists() the $album->artist no longer works. I have also tried $album->commonModelsArtists()

I have looked for examples but cannot find any. Any idea's?



47.7k
Accepted
answer

In the relationship I needed to defined an alias so in Albums:

    $this->belongsTo("artist_id", "Common\Models\Artists", "id", array(
        "foreignKey" => array(
            "message" => "You cannot save the album as the artist no longer exists!"
        ),
        "alias" => "Artists"
    ));