简体   繁体   中英

Yii joining two table using relations in model

Hi I have these two tables that I want to join using relations in Yii, The problem is Im having a hard time figuring out how Yii relation works.

picturepost
    id
    title
    link_stat_id

linkstat
    id
    link
    post_count

I also have a working SQL query. This is the query I want my relation to result when I search when I want to get picturepost

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

I want something like this when I search for a post.

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

Here's my table for extra info:

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;

Thanks in advance I hope I explained it clearly.

There are a few tutorial regarding this, and I won't repeat them, but urge you to check them out.

The easiest starting point will be to create your foreign key constraints in the database, then use the Gii tool to generate the code for the model, in this case for the table picturepost .

This should result in a class Picturepost with a method relations(),

class Picturepost extends  {

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

This links the 2 tables using the *link_stat_id* field as the foreign key (to the primary key of the linked table).

When you are querying the table picturepost, you can automatically pull in the linkstat records.

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

// picturepost_linkstats is the relationship name
$linkstats_records =  $picturepost->picturepost_linkstats;
public function relations()
{
   return array(
     'linkstat' => array(self::HAS_ONE, 'Linkstat', array('link_stat_id'=>'link')),
   );
}

More on yii relations .

This assumes that you have an active record model Linkstat that represents data in table linkstat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM