我有一个DB,它有一个post表、一个内容表和一个空格表。
post是一种内容类型,空间是许多帖子的容器。我想把所有的帖子都放在一个空间里。
员额:
id object_id
--------------
1 22内容(object_id -> post.id):
id space_id
------------------------
22 3空间(id -> content.space_id):
id
--------------
3要在空间中获得posts,控制器函数如下所示:
$posts = Post::find()
->joinWith('content', false)
->where(['{{content}}.space_id' => $space_id])
->all();Post模型具有这样的功能,用于获取post的内容对象:
public function getContent() {
return $this->hasOne(Content::className(), ['object_id' => 'id'])->andOnCondition(['{{content}}.object_model' => 'humhub\modules\post\models\Post']);
}在数据库架构改变之前,这是非常有效的。
现在,内容表中不再有space_id列。相反,有一个新的表contentcontainer,它有一个pk字段代替space_id,还有一个class字段(即space类)来标识PK是一个空格(表中还有一个class )。
现在的表/关系是:
邮寄表:
id object_id
--------------
1 22内容表(object_id -> post.id):
id contentcontainer_id
------------------------
22 5内容容器表(id -> content.contentcontainer_id)
id pk class
---------------
5 3 //Space空间(id ->内容容器):
id
--------------
3要获得一个空间内的所有帖子,我现在必须链接3个表: post、content、contentcontainer。
我是否将内容容器关系添加到Post模型?还是修改Post模型中的内容模型关系?不知道如何最好地解决而不写一个大的草率的查询。
我将控制器函数更改为:
$posts = Post::find()
->where(['{{contentcontainer}}.pk' => $space_id])
->andWhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\Space'])不确定这是否正确,我在Post模型中设置了Post关系。
发布于 2017-07-09 14:59:51
我是这样解决这个问题的(结果来自内容模型,而不是Post模型):
$content = Content::find()
->joinWith('contentContainer')
->andWhere(['{{contentcontainer}}.pk' => $space_id])
->andWhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\Space'])
->andWhere(['{{content}}.object_model' => 'humhub\modules\post\models\Post'])
->asArray()
->all();发布于 2017-04-05 20:29:06
好像你有一个连接表- contentcontainer。在官方Yii2 docs 如何通过连接表来分解关系中有一个例子。
在您的例子中,Post模型中的关系可能如下所示:
public function getItems()
{
return $this->hasMany(Content::className(), ['id' => 'pk'])
->viaTable('contentcontainer', ['class' => 'space_id']);
}现在,您的控制器函数将使$posts执行两个连接,insead为一个。
发布于 2017-04-06 13:49:18
在Space模型中创建此方法:
public function getPosts() {
return Post::find()
->innerJoin('contentcontainer', ['and',
'contentcontainer.pk = space.id',
'contentcontainer.class = "humhub\modules\space\models\Space"'])
->innerJoin('content', 'content.contentcontainer_id = contentcontainer.id')
->innerJoin('post', 'post.object_id = content.id');
}https://stackoverflow.com/questions/43238287
复制相似问题