1
votes

I have videos and artists, video belongsTo artist and artist hasMany videos.

I did it and is working, when I find videos and set [contain => ['Artists'] I got the result videos entity with the related artist.

This first relationship is about the artist that is the "owner" of the video, but I need another relationship because a video could have N others artists "featuring" the video.

Heres a better overview:

Tables:

videos: id (pk), artist_id (fk)

artists_videos: video_Id (pk), artist_id (pk)

artists: id (pk)

-

Heres the code:

//VideosTable
$this->BelongsTo('Artists');
$this->belongsToMany('Artists');

//ArtistsTable
$this->hasMany('Videos');
$this->belongsToMany('Videos');

The issue is, when I set this second relationship the first relationship stops to work, I think is happening some kind of collision.

2

2 Answers

1
votes

You need to call these associations with different names:

$this->belongsTo('Comments', [
            'className' => 'Comments',
            ...
        ]);

$this->hasMany('UnapprovedComments', [
            'className' => 'Comments',
            ...
        ]);

... so they're treated by the ORM as separate instances.

0
votes

You can try this since you defined "videos" belongsToMany "artists" [As per your Tables] and artists hasMany videos

In the Videos Table:

$this->belongsTo('Artists', [
            'foreignKey' => 'artist_id'
        ]);

$this->belongsToMany('Artists', [
            'foreignKey' => 'video_id',
            'targetForeignKey' => 'artist_id',
            'joinTable' => 'artists_videos'
        ]);

In the Artists Table:

$this->hasMany('Videos', [
                'foreignKey' => 'artist_id'
            ]);
$this->belongsToMany('Videos', [
            'foreignKey' => 'artist_id',
            'targetForeignKey' => 'video_id',
            'joinTable' => 'artists_videos'
        ]);

you can check the example at CakePHP Examples

Then try from the CakeDoc

$this->hasMany('Comments', [
        'className' => 'Comments',
        'conditions' => ['approved' => true]
    ]);

    $this->hasMany('UnapprovedComments', [
        'className' => 'Comments',
        'conditions' => ['approved' => false],
        'propertyName' => 'unnaproved_comments'
    ]);