Ad

OctoberCMS, How To Define Relationship With Children Model?

- 1 answer

I need render children model in template, my parent model "Form" haves db field "field_id", where field_id equals id children model "Field". How can I access the child model? I tried add relation to Field model:

public $hasOne = [
        'field' => ['\Webfather\Services\Models\Variation', 'key' => 'field_id']
    ];

and tried display in template:

{{form.field.name}}

but form.field was empty

Ad

Answer

your relation linking is wrong.

what you need to do is, you need to define form_id inside your child model(Variation)

you need to insert form_id => 'parent model (Form) id' there

then inside Form model

public $hasOne = [
    'field' => ['\Webfather\Services\Models\Variation', 'key' => 'form_id']
];

so now it will search child model(Variation) where form_id = id of parent Form

and then you can get child record.

OR to make it working with current scenario you need to make Form model as child. (less code changes)

then inside Form model

public $belongsTo = [
    'field' => ['\Webfather\Services\Models\Variation', 'key' => 'field_id']
];

now you can use

{{form.field.name}}
Ad
source: stackoverflow.com
Ad