我正在尝试设计字典。这些表是:
-- 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
表中关系的左侧还是右侧。任何建议,将不胜感激!
这是适应您的查询的问题(查询是key
还是otherKey
等于您的单词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