Yii在模型中使用关系连接两个表

g6baxovj  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(116)

嗨,我有这两个表,我想在Yii中使用关系连接,问题是我有一个很难弄清楚Yii关系是如何工作的。

picturepost
    id
    title
    link_stat_id

linkstat
    id
    link
    post_count

我还有一个有效的SQL查询。这是我希望我的关系在我搜索时得到的查询,当我想得到picturepost

SELECT picturepost.id, picturepost.title,linkstat.post_count   
FROM picturepost
RIGHT JOIN linkstat
ON picturepost.link_stat_id=linkstat.link;

当我搜索帖子时,我希望有这样的东西。

$post = PicturePost::model() -> findByPk($id);
echo $post->linkCount;

以下是我的表格,可供您了解更多信息:

CREATE TABLE IF NOT EXISTS `picturepost` (
    `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `title` text COLLATE utf8_unicode_ci DEFAULT NULL,
     `link_stat_id` char(64) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM;
CREATE TABLE IF NOT EXISTS `linkstat` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `link` char(64) COLLATE utf8_unicode_ci NOT NULL,
  `post_count` int(11) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `post_count` (`post_count`),
  KEY `link_stat_id` (`link`)
) ENGINE=InnoDB;

提前感谢我希望我解释清楚了。

yhived7q

yhived7q1#

有一些关于这方面的教程,我不会重复它们,但敦促您检查它们。
最简单的起点是在数据库中创建外键约束,然后使用Gii工具生成模型的代码,在本例中是表 picturepost
这将产生一个带有方法relations()的Picturepost类,

class Picturepost extends  {

public function relations()
{
   return array(
     'picturepost_linkstats' => array(self::HAS_MANY, 
                                 'linkstat', 'link_stat_id'),
   );
}

这将使用 link_stat_id 字段作为外键(链接到链接表的主键)来链接这两个表。
当您查询表PicturePost时,可以自动拉入Linkstat记录。

// Get the picturepost entry
$picturepost = PicturePost::model()->findByPk(1);

// picturepost_linkstats is the relationship name
$linkstats_records =  $picturepost->picturepost_linkstats;
mzaanser

mzaanser2#

public function relations()
{
   return array(
     'linkstat' => array(self::HAS_ONE, 'Linkstat', array('link_stat_id'=>'link')),
   );
}

有关yii relations的更多信息。
这假定您有一个活动记录模型Linkstat,它表示表linkstat中的数据。

相关问题