【问题标题】:OctoberCMS: Manage a two-way many-to-many relationshipOctoberCMS:管理双向多对多关系
【发布时间】:2020-01-02 13:20:29
【问题描述】:

我正在尝试设计一本字典。这些表格是:

-- 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 表中关系的左侧还是右侧。

【问题讨论】:

    标签: php laravel octobercms


    【解决方案1】:

    这是一个调整你的查询的问题(查询它是否是keyotherKey 等于你的单词id),只需执行规则key < otherKey,你就会获得唯一性。

    看看这篇文章 使用相同的方法声明两个用户之间的关系。 Social network

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

    查询看起来像这样

    $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
    

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 2015-09-11
      • 2013-04-13
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      相关资源
      最近更新 更多