octobercms / october

Self-hosted CMS platform based on the Laravel PHP Framework.
https://octobercms.com/
Other
11.01k stars 2.21k forks source link

Call to a member function getKey() on null #5777

Closed ssi-com-pl closed 7 months ago

ssi-com-pl commented 7 months ago

Hi! When I click Link / Unlink in relation field (flats), I get an error: "Call to a member function getKey() on null" on line 7 of \modules\backend\behaviors\relationcontroller\partials_toolbar.php

models/Investments.php

class Investments extends Model
{
    public $hasMany = [
        'flats' => [\MyPlugin\Flats\Models\Flats::class, 'key' => 'investments_id']
    ];

models/investments/fields.yaml

flats:
      label: Flats
      type: relation

models/Flats.php

class Flats extends Model
{
    public $belongsTo = [
        'investment' => [\MyPlugin\Flats\Models\Investments::class, 'key' => 'investments_id'],
    ];

models/flats/fields.yaml

investment:
      label: Investment
      type: relation
daftspunk commented 7 months ago

Hey @ssi-com-pl Try setting default to true in the relation definition so it has an empty model set when the relation is empty.

public $belongsTo = [
    'investment' => [
        \MyPlugin\Flats\Models\Investments::class,
        'key' => 'investments_id',
        'default' => true
    ],
];

Link to docs is here: https://docs.octobercms.com/3.x/extend/database/relations.html#default-models

I hope this helps!