Simple usage example of related query in Yii2_php example

WBOY
Release: 2016-08-17 13:02:30
Original
948 people have browsed it

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']);
}

Copy after login

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();
}

Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!