簡體   English   中英

OctoberCMS:管理雙向多對多關系

[英]OctoberCMS: Manage a two-way many-to-many relationship

我正在嘗試設計一本字典。 這些表是:

-- Languages
create table meysam_dictionary_languages
(
    id int unsigned auto_increment
        primary key,
    title varchar(50) not null
)

-- Words
create table meysam_dictionary_words
(
    id int unsigned auto_increment
        primary key,
    word varchar(500) not null,
    lang_id int unsigned not null
)

-- Translations
create table meysam_dictionary_translations
(
    left_word_id int unsigned not null,
    right_word_id int unsigned not null,
    description varchar(500) not null
)

現在每個Word都可以有多種含義。 因此,單詞之間存在多對多關系。 此關系存儲在Translations表中。 這是我的Word模型:

class Word extends Model
{
    public $belongsTo = [
        'language' => [
            'Meysam\Dictionary\Models\Language',
            'key' => 'lang_id'
        ]
    ];

    public $belongsToMany = [
        'meanings' => [
            'Meysam\Dictionary\Models\Word',
            'table'    => 'meysam_dictionary_translations',
            'key'      => 'left_word_id',
            'otherKey' => 'right_word_id'
        ],
    ];
}

鑒於上述$belongsToMany關系,在Word控制器頁面中,如果單詞 ID 在Translations表中關系的左側,我只能看到單詞的含義。 但如果該詞在關系的右側,則不會顯示其相關詞。 有什么解決方法嗎?

我需要一個詞的相關詞顯示在控制器頁面中,而不管該詞位於Translations表中關系的左側還是右側。

這是調整您的查詢的問題(查詢是否是keyotherKey等於您的單詞 id),只需實現規則key < otherKey ,您將獲得key < otherKey

看看這篇文章,用同樣的方法來聲明兩個用戶之間的關系。 社交網絡

在該示例中,您將不需要“操作”字段。

查詢看起來像這樣

$languageId = 1;
$wordId = 1;
$query = 'SELECT * FROM words RIGHT JOIN (SELECT `key`, other_key FROM `meysam_dictionary_translations` WHERE (`key` = '.$wordId.' OR `other_key` = '.$wordId.') AND language_id = '.$languageId.') as r on words.id = r.key OR words.id = r.other_key WHERE workds.id!='.$wordId

暫無
暫無

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

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