Junction table, one-to->many,many-to-many, and link()



well, I have a problem, I wanted to learn working in some PHP framework, and after days and days of search i decided Yii is probably most intuitive, easiest to setup, and great overall.

So I asked my college professor for advice, and he said that good start for learning would be our college example that we have worked when we learned PHP:


Creating Albums that each logged in user can view, but only creator can add, edit or delete Images from his albums.

This is assigned data model:

postimg.org/image/km16ikbt9 (new forum user, can’t share links)

So User can have many albums, One album has one User

Album has many Images, and Images have one Album

[size="1"]P.S. user-image is record when did user last saw image, but I am not implementing that now[/size]

So I tried to create Controllers and Forms in a way that when I create new Album, I wanted to automatically create data in album_user table. Using standard PHP this was fairly simple. Using Yii, it isn’t for me beginner.

Main problem is finding documentation and forums on link() method, since it shares name with link-URL.

In documentation it, says yii-db-baseactiverecord.html#link()-detail (can’t share links)

public void link ( $name, $model, $extraColumns = [] )

and when I insert this method in


link('album-user', $model, ['user_id' => Yii::$app->user->id]);...

I get error - Link is accepting exactly 2 parameters not 3. Since I tried million combinations, changing to two parameters, etc. all to strings but nothing worked for me.

And since CRUD generator didn’t create method getUser in Album.php model I added that code, and changed that tens of times, using ViaTable,Via and lot of stuff but nothing worked.


     * @return \yii\db\ActiveQuery


    public function getAlbumImages()


        return $this->hasMany(AlbumImage::className(), ['album_id' => 'id']);



     * @return \yii\db\ActiveQuery


    public function getAlbumUser()


        return $this->hasOne(AlbumUser::className(), ['album_id' => 'id']);



        public function getUser()


        return $this->hasMany(User::className(), ['id' => 'album_id'])





Bypassed Solution

So i edited Entities and relationships like this:

postimg.org/image/6knkvagpf/(can’t share links replace space with dot)

and it works now, but it is wrong practice, bending the rules, and I will have to create some many to many connections before or later, so i would like to know how to do it properly.

Hope you can explain it to me, or give some link :D, since I have had hard time googling Yii link() :D

Guide >> Working with Database >> ActiveRecord >> Saving Relations

You have to use "The Definitive Guide" as the first source.