簡體   English   中英

如何使用CakePHP3定義多對多關系?

[英]How to define a Many-To-Many relationship using CakePHP3?

我想在CakePHP 3的三個表之間創建多對多關系。通過在我的控制器和模型中定義此關系,但是我做不到。

我的三個表如下:

表一:用戶

ID   Name
1    gert
2    henk

表二:衣服

ID   Name
1    jacket
2    jeans

這是我保存“用戶”表和“衣服”表之間的鏈接的表。 因此,一個用戶現在可以擁有多件衣服,而不同的衣服可以屬於多個用戶。

表三:Users_has_clothes

ID   UserId(forKey)   ClothesId(forKey)
1    1                1
2    2                1
3    1                2

我已經嘗試使用“通過”選項按照CakePHP官方網站上的說明進行操作,但是我仍然不清楚。

如果您的聯接表沒有多余的字段(在您的示例中看起來沒有),則不應使用through選項。

如果可以,則應遵循CakePHP命名約定,這意味着users_clothes表應命名為users_clothes ,其兩個字段應為user_idclothe_id 有關命名約定的更多詳細信息,請參見CakePHP文檔 使用這些約定,以下代碼將起作用:

public class User extends Table {
    public function initialize (array $config) {
         $this->belongsToMany('Clothes');
    }
}
// Same for table Clothe

如果確實需要將名稱保留為當前名稱,則應添加以下額外選項:

public class User extends Table {
    public function initialize (array $config) {
         $this->belongsToMany('Clothes', [
            'joinTable' => 'Users_has_clothes',
            'foreignKey' => 'UserId', 
            'targetForeignKey' => 'ClotheId'
        ]);
    }
}
// Same for Clothe (switch foreignKey and targetForeignKey)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM