Home  >  Article  >  Backend Development  >  Simple usage example of related query in Yii2_php example

Simple usage example of related query in Yii2_php example

WBOY
WBOYOriginal
2016-08-17 13:02:30926browse

The example in this article describes the usage of associated query in Yii2. Share it with everyone for your reference, the details are as follows:

There are two tables, post and category, post.cate_id corresponds to category.id

Use Gii to increase the models of these two tables

Then the model of the post has the following code

public function getCate()
{
  return $this->hasOne(Category::className(), ['id' => 'cate_id']);
}

Add the following method at the bottom of the post model to get the content of the association table

public static function getPostsByCategory($cate_id)
{
  return Post::find()
    ->joinWith('cate')
    ->where(['post.cate_id'=>$cate_id])
    ->asArray()
    ->all();
}

Readers who are interested in more Yii-related content can check out the special topics of this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent Development Framework of PHP", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string (string) usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will help you design PHP programs based on the Yii framework.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn