differnece between hasmany() and hasone()

Hi guys,

I’m al ittle bit confused about Gii generating relationships. In my database, all cardinalites are 1:n. This is,because no foreign key has been defined as unique.

Nevertheless, gii produced a relationship in table bewerber like this







    public function getPerson() {

        return $this->hasone(\common\modules\basis\models\Person::className(), ['id' => 'id_person']);

    }

    }



and in table person like this





    public function getBewerbers() {

        return $this->hasMany(\frontend\modules\bewerber\models\Bewerber::className(), ['aktualisiert_von' => 'id']);

    }



What is diffrence between these methods defining relationships. Why is Gii creating two different relationships?

Moigrationscript relationships are based on is like this for person:





  $this->createTable('person', [

            'id' => $this->primaryKey(),

.

.

.


                ], $tableOptions);



and this for bewerber





        $this->createTable('bewerber', [

            'id' => $this->primaryKey(),

            'id_person' => $this->integer(10),

.

.

            'FOREIGN KEY ([[id_person]]) REFERENCES person ([[id]]) ON DELETE CASCADE ON UPDATE CASCADE',

.

.

                ], $tableOptions);



I think it make sense if you see it like a Bewer belongs to a person and a person could have many Bewers, so when you define that foreign key on bewers table gii will read the meta data and generate the required methods for you.

why gii generates 2 methods imagine you have a listview that displays bewers and the name of the person it belongs to, the relationship works other way around as well if you are displaying user you might wanna list all his bewers.




// Bewer model

public function getPerson()

{

// ...

}




// Person model

public function getBewerbers()

{

// ...

}

Okay.Thx for this information. As i know now, Gii will implement at tabel having ForeignKey hasmany() and at table having PrimaryKey hasOne-method…

Hi,

Additionally I think it is pretty well explained here:

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#declaring-relations

If you don’t know the guide already I would suggest to keep the link open in a tab. ;)

It’s a pretty good ressource to get an idea how things work and should be done.

Best Regards