I try to use relationShip ManyToMany with PHP Pahlcon 3.4
My models :
use PhalconMvcModel; class Societe extends Model { public $id; public $nom; public $adresse1; public $adresse2; public $code_postal; public $ville; public $pays; public $siret; public $numero_tva; public $created_at; public $updated_at; public function initialize() { $this->setSource('societies'); $this->hasMany( 'id', 'StatementModelSocietesBanques', 'societe_id' ); }
and Banque :
use PhalconMvcModel; class Banque extends Model { public $id; public $nom; public function initialize() { $this->setSource('banques'); $this->hasMany( 'id', 'StatementModelSocietesBanques', 'banque_id' ); }
and relation :
use PhalconMvcModel; class SocietesBanques extends Model { public $id; public $societe_id; public $banque_id; public function initialize() { $this->setSource('societes_banques'); $this->belongsTo( 'societe_id', 'StatementModelSociete', 'id' ); $this->belongsTo( 'banque_id', 'StatementModelBanque', 'id' ); }
I can save in table societes_banques, but not get data
In my controller, I get my Societe object :
$societe = Societe::findFirst($id);
After, I try to get SocietesBanques data with :
$societe->societesBanques
This line return me NULL
If I try :
$societe->getSocietesBanques()
I have the error :
The method 'getSocietesBanques' doesn't exist on model 'StatementModelSociete'
I do same thing as Phalcon documentation
Can you help me? what is my fault?
Advertisement
Answer
Because you didn’t specified an alias during relation declaration.
class Societe extends Model { public function initialize() { $this->setSource('societies'); $this->hasMany( 'id', 'StatementModelSocietesBanques', 'societe_id', [ 'alias' => 'societesBanques', // 4th parameter as array ] ); }
And after that, you can call magic method getSocietesBanques()
.