我如何从关系表中选择列?
$orders=Category::find()
->joinWith('posts')
->all();
我试过了
$orders=Category::find()
->select('post.*')
->joinWith('posts')
->all()
等,但我得到错误: 获取未知属性:common\models\Category::id_post
Excecute Sql statment : SELECT `post`.* FROM `category` LEFT JOIN `post` ON `category`.`id_category` = `post`.`id_categoryFK`
但我不能使用表格帖子中的列 我想从连接表中写入数据
最佳答案
在这个 Yii2 Wiki Article 中有一个很好的解释.但我会根据您的意见简化那篇文章。
您可能有两个要加入的模型:common\models\Category
和 common\models\Post
,所有属性都与数据库中的属性相匹配。另外,假设 Category
有很多 Post
与之关联,但是 Post
只有 一个 类别
。
1。在模型中定义关系
首先你必须让 Yii2 理解两个模型之间的关系。 Yii2 会做一些魔术来帮助您加入表格,但您必须首先设置模型。
1.1 编辑类别
模型
在 common\models\Category
中添加以下行:
/**
* @return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Posts::className(), ['category_id' => 'id_categoryFK']);
}
1.2 编辑Post
模型
在 common\models\Post
中添加以下行:
/**
* @return \yii\db\ActiveQuery
*/
public function getCategory()
{
return $this->hasOne(Post::className(), ['id_categoryFK' => 'category_id']);
}
2。检索数据
现在,您可以从任何 Controller 像这样使用它:
/* 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。继续学习
正如我一开始所说,这个 Yii2 Wiki Article将在大多数情况下为您提供帮助。这个其他Yii2 official guide , 也很好。
编码愉快!
关于php - Yii2 从两个表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747629/