有 2 个表多到曼蒂和另一个中间人能够
$this->createTable('tweet',[
'id' => Schema::TYPE_PK,
'text' => Schema::TYPE_STRING.' NOT NULL',
'date_written' => Schema::TYPE_STRING.' NOT NULL',
'date_imported' => Schema::TYPE_STRING.' NOT NULL',
],"ENGINE=InnoDB DEFAULT CHARSET=utf8");
$this->createTable('hashtag',[
'text' => $this->string(),
'PRIMARY KEY(text)'
],"ENGINE=InnoDB DEFAULT CHARSET=utf8");
$this->createTable('tweet_hashtag', [
'tweet_id' => $this->integer(),
'hashtag_text' => $this->string(),
'PRIMARY KEY(tweet_id, hashtag_text)'
],"ENGINE=InnoDB DEFAULT CHARSET=utf8");
$this->createIndex('idx-tweet_hashtag-tweet_id', 'tweet_hashtag', 'tweet_id');
$this->createIndex('idx-tweet_hashtag-hashtag_text', 'tweet_hashtag', 'hashtag_text');
$this->addForeignKey('fk-tweet_hashtag-tweet_id', 'tweet_hashtag', 'tweet_id', 'tweet', 'id', 'CASCADE');
$this->addForeignKey('fk-tweet_hashtag-hashtag_text', 'tweet_hashtag', 'hashtag_text', 'hashtag', 'text', 'CASCADE');
表推文
public function getTweetHashtags()
{
return $this->hasMany(TweetHashtag::className(), ['tweet_id' => 'id']);
}
public function getHashtagTexts()
{
return $this->hasMany(Hashtag::className(), ['text' => 'hashtag_text'])->viaTable('tweet_hashtag', ['tweet_id' => 'id']);
}
表tweet_hashtag
public function getHashtagText()
{
return $this->hasOne(Hashtag::className(), ['text' => 'hashtag_text']);
}
public function getTweet()
{
return $this->hasOne(Tweet::className(), ['id' => 'tweet_id']);
}
表主题标签
public function getTweetHashtags()
{
return $this->hasMany(TweetHashtag::className(), ['hashtag_text' => 'text']);
}
public function getTweets()
{
return $this->hasMany(Tweet::className(), ['id' => 'tweet_id'])->viaTable('tweet_hashtag', ['hashtag_text' => 'text']);
}
当我尝试时 Tweet::find()->with('hashtag')->where(['id' => $tweetID])->all()
有例外
Exception 'yii'base'InvalidParamException' with message 'app'models'Tweet has no relation named "hashtag".'
我如何才能正确地进行加载。要从话题标签表中获取"文本",请按推文表中的 id 获取。
你应该使用名称或关系
Tweet::find()->with('tweetHashtags')->where(['id' => $tweetID])->all()