Yii2 query for posts in a space -


i had db post table, content table, , space table.

a post type of content, , space container many posts. want posts within space.

post:

id   object_id -------------- 1    22 

content (object_id --> post.id):

id   space_id ------------------------ 22   3 

space (id --> content.space_id):

id    -------------- 3 

to posts within space, controller function looked this:

$posts = post::find()   ->joinwith('content', false)   ->where(['{{content}}.space_id' => $space_id])   ->all(); 

and post model had function content object post:

public function getcontent() {    return $this->hasone(content::classname(), ['object_id' => 'id'])->andoncondition(['{{content}}.object_model' => 'humhub\modules\post\models\post']); } 

this worked until database schema changed.

now there no longer space_id column in content table. instead, there new table contentcontainer pk field replaces space_id, , class field (i.e. space class) identify pk space( there class in table).

the tables/relationships now:

post table:

id   object_id -------------- 1    22 

content table (object_id --> post.id):

id   contentcontainer_id ------------------------ 22   5 

contentcontainer table (id --> content.contentcontainer_id)

id   pk   class --------------- 5    3    //space 

space (id --> contentcontainer):

id    -------------- 3 

to posts within space, have link 3 tables: post,content,contentcontainer.

do add contentcontainer relationship post model? or modify content model relationship in post model? not sure how best tackle without writing big sloppy query.

i changed controller function this:

$posts = post::find()   ->where(['{{contentcontainer}}.pk' => $space_id])   ->andwhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\space']) 

not sure right , stuck setting contentcontainer relationship in post model.

seems have junction table - contentcontainer. there example in official yii2 docs how decalre relation via junction table.

in case relation in post model this:

public function getitems() {     return $this->hasmany(content::classname(), ['id' => 'pk'])         ->viatable('contentcontainer', ['class' => 'space_id']); } 

now controller function $posts doing 2 joins insead of one.


Comments