1

I built up a plugin and inside the plugin I created the relation between Entry and Section using ActiveRecord, like below:

In SectionRecord :

class SectionRecord extends ActiveRecord
{
    public static function tableName()
    {
        return '{{sections}}';
    }

    public function getEntries()
    {
        return $this->hasMany(EntryRecord::className(),['id' => 'sectionId']);
    }
}

In EntryRecord file:

class EntryRecord extends ActiveRecord
{
    public static function tableName()
    {
        return '{{entries}}';
    }

    public function getSection()
    {
        return $this->hasOne(SectionRecord::className(),['sectionId' => 'id']);
    }
}

At last in controller:

$hub = SectionRecord::findOne(['handle'=>'hub']);
dd($hub->entries);

I tried to get section which is working, but when I wanna fetch entries under that section, showed me an error:

Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: raintestplugin\test\records\SectionRecord::sectionId
1

Because the property sectionId does not exist in the sections table. All models in Craft have the property id as their primary key not - for example - sectionId

5
  • Yes, there is an "id" as primary key, but there also is "sectionId" column which I wanna use to join with "Entry" table. Do you mean only primary key can be used to join tables together?
    – yu xia
    Mar 20 '18 at 19:54
  • No I mean your section has only the property id not sectionId.. as you can see here yiiframework.com/doc-2.0/… "An easy rule to remember this is, as you see in the example above, you write the column that belongs to the related Active Record directly next to it. You see there that customer_id is a property of Order and id is a property of Customer." But the section does not have the property sectionId only id. However I'm not sure why you even need those functions since they already exist Mar 20 '18 at 20:40
  • I'm new to craft and I wanna get all the entries under a certain section, so I tried to join "Entries" table and "Sections" table. "sectionId" belong to "Entries" table if you check the database. I run the sql below is working, but I don't know what's going wrong in craft: select * from entries join sections on entries."sectionId"=sections.id
    – yu xia
    Mar 20 '18 at 21:08
  • $entries = craft\elements\Entry::find()->sectionId(>>insert your id<<)->all(); will do the trick and $section = $entry->getSection() you usually don't need to join anything Mar 20 '18 at 21:12
  • Thanks man! that's another way. Because I'm new, so I wanna try different ways to play around with craft including writing query, the way you mentioned and active records. XD
    – yu xia
    Mar 20 '18 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.