I'm creating a plugin and I need help to query relational data.
Here's the table schema I have:
collection
+----+-------------+---------------------+---------------------+-----+
| id | label | dateCreated | dateUpdated | uid |
+----+-------------+---------------------+---------------------+-----+
| 1 | Static page | 2016-03-11 16:19:07 | 2016-03-11 16:19:07 | 0 |
+----+-------------+---------------------+---------------------+-----+
collection_section
+----+---------------+-----------+---------------------+---------------------+-----+
| id | collectionId | sectionId | dateCreated | dateUpdated | uid |
+----+---------------+-----------+---------------------+---------------------+-----+
| 1 | 1 | 16 | 2016-03-11 16:19:07 | 2016-03-11 16:19:07 | 0 |
| 2 | 1 | 9 | 2016-03-11 16:19:07 | 2016-03-11 16:19:07 | 0 |
| 3 | 1 | 14 | 2016-03-11 16:19:07 | 2016-03-11 16:19:07 | 0 |
| 4 | 1 | 10 | 2016-03-11 16:19:07 | 2016-03-11 16:19:07 | 0 |
+----+---------------+-----------+---------------------+---------------------+-----+
craft_content
+------------+
| title |
+------------+
| mytitle |
+------------+
I've created 2 records:
// collectionRecord
public function defineRelations()
{
return array(
'collectionSection' => array(
static::HAS_MANY,
'collectionSectionRecord',
'sectionId'
)
);
}
// collectionSectionRecord
public function defineRelations()
{
return array(
'collection' => array(
static::BELONGS_TO,
'collectionRecord',
'required' => true,
'onDelete' => static::CASCADE
),
'section' => array(
static::BELONGS_TO,
'SectionRecord',
'required' => true,
'onDelete' => static::CASCADE
),
);
}
The section ids are only singles and I need to get a listing of all the sections with their content related to the collectionId.
I tried this:
$query = craft()->db->createCommand()
->select('s.*')
->from('sections s')
->join('collection_section cs', 'cs.sectionId = s.id')
->where(array('cs.collectionId' => 1))
->queryAll();
return SectionModel::populateModels($query);
I actually get the sections from the craft_sections table but I need the related content (title row) "mytitle" in the craft_content table. Is there an easy way to do that in Craft?