Storing Related Models

I have read same disussions of these topic here in forum, but I have still some problems. I tried to do this example from doc http://docs.phalconphp.com/en/latest/reference/models.html#storing-related-records But I get a error that artist_id can not be null I have defined the relations:

class Artists {
public $id;
public $name;
...
$this->hasMany('id', 'Albums', 'artist');

and

class Albums {
public $id;
public $name;
public $artist_id;
...
$this->belongsTo('artists_id', 'Artists', 'id');


3.2k

Try to had alias in relation :

class Artists {
public $id;
public $name;
...
$this->hasMany('id', 'Albums', 'artist', array('alias' => 'album'));
class Albums {
public $id;
public $name;
public $artist_id;
...
$this->belongsTo('artists_id', 'Artists', 'id', array('alias' => 'artist'));


417

I also have tried this. But I got the same error.



417
edited Oct '14

Sorry, I have simplified the Probelm of the example in the doc, but I see that there seems to be a kritical difference. But in my special case I have:

class Artists {
public $id;
public $name;
public $main_album;
...
$this->hasOne('main_album', 'Albums', 'id');
class Albums {
public $id;
public $name;
public $artist;
...
$this->belongsTo('artist', 'Artists', 'id');
$album = new Albums();
$ablum->name='Test';

$artist = new Artist();
$artist->name='An Artist';
$artist->artists=$album;//here I use the Name of the hasOne Relation


417

I think, I should solve this problem with assigning the Ids. But I have another problem in this context. When I have a Model A, with a b_id column und a Model B. If I assign the Relation in this way:

$this->hasOne('b_id', 'ModelB', 'id');

But $modelA->modelB=$modelB seems not to work, I get the error that b_id can not be null. How a 1:1 Relation must be declared?



18.5k

I think it's in the other way:

$this->hasOne('id', 'ModelB', 'this_id');


417

So there is no way, to have the relation cloumn in ModelA? Or belongsTo must be used?



18.5k

You're doing it well: you use hasOne(...) in the two models. It would be OK doing:

ModelA
$this->hasOne('id', 'ModelB', 'a_id');

ModelB
$this->hasOne('id', 'ModelA', 'b_id');


417

two columns for one relation?



18.5k

Yeah; modelA has a column that points to a record of ModelB, and the same in the other way. You said that is a 1:1 relationship, so you need to specify a column in each model that points to the referenced ID (or whatever it references) in the other model. If you don't do that, how you can know which record owns which record?



417

ModelA:

id name b_id

ModelB id name

when ModelB is related to ModelA then i can query in ModelA with WHERE b_id = id, or something like that. So 2 colums would be redundant



18.5k

Then you will put hasOne(...) in ModelB and belongsTo(...) in ModelA.