简体   繁体   English

Yii2从两个表中选择数据

[英]Yii2 Select data from two tables

how I can choose columns from relation table ? 我如何从关系表中选择列?

$orders=Category::find()
->joinWith('posts')
->all();

I tried yet 我试过了

$orders=Category::find()
->select('post.*')
->joinWith('posts')
->all() 

etc, but i gets error: Getting unknown property: common\\models\\Category::id_post 等,但我得到错误:获取未知属性:common \\ models \\ Category :: id_post

Excecute Sql statment : SELECT `post`.* FROM `category` LEFT JOIN `post` ON `category`.`id_category` = `post`.`id_categoryFK`

but i can't using columns from table post I would like to write data from the joined tables 但我不能使用表格中的列我想从连接表中写入数据

There is a really good explanation in this Yii2 Wiki Article . 这篇Yii2维基文章中有一个非常好的解释。 But I will simplify that article, using your input. 但我会使用您的输入简化该文章。

You probably have two models that you want to join: common\\models\\Category and common\\models\\Post with all the attributes matching the ones in the Database. 您可能有两个要加入的common\\models\\Categorycommon\\models\\Categorycommon\\models\\Post ,其所有属性都与数据库中的属性相匹配。 Also, let's say that Category has many Post s associated to it, but a Post only has one Category . 此外,让我们说, Category 有很多 Post伴生它,但一个Post 只有一个 Category

1. Define the relations in the Models 1.定义模型中的关系

First you have to make Yii2 to understand that there is a relation between two Models. 首先,你必须让Yii2理解两个模型之间存在关系。 Yii2 will do some magic to help you join the tables, but you have to setup the models fist. Yii2会做一些魔术来帮助你加入表格,但你必须设置模型。

1.1 Editing Category Model 1.1编辑Category模型

In common\\models\\Category add the following lines: common\\models\\Category添加以下行:

/**
 * @return \yii\db\ActiveQuery
 */
public function getPosts()
{
    return $this->hasMany(Posts::className(), ['category_id' => 'id_categoryFK']);
}

1.2 Editing Post Model 1.2编辑Post模型

In common\\models\\Post add the following lines: common\\models\\Post添加以下行:

/**
 * @return \yii\db\ActiveQuery
 */
public function getCategory()
{
    return $this->hasOne(Post::className(), ['id_categoryFK' => 'category_id']);
}

2. Retrieve the data 2.检索数据

Now, from any controller you can use it like this: 现在,从任何控制器,您可以像这样使用它:

/* Access posts from a category*/
$category = common\models\Category::find()->where(['category_id'=>$category_id])->one();
foreach($category->posts as $post) // iterate over all associated posts of category
{
    $postTitle = $post->title; //access data of Post model
}

/* Access category from post */
$post = common\models\Post::find()->where(['id'=>$post_id])->one();
$categoryName = $post->category->category_name;

3. Keep learning 3.继续学习

As I said in the beginning, this Yii2 Wiki Article will help you in most of your cases. 正如我在开始时所说,这个Yii2 Wiki文章将在大多数情况下为您提供帮助。 This other Yii2 official guide , is very good too. 这个其他的Yii2官方指南 ,也很好。

Happy coding! 快乐的编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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