F
Filament7mo ago
Amitoj

HasOne relationship not updating foreignKey in parent model

Hi there, I have two models, Project & ProjectAttachment. The relation in Project model is:
protected $fillable = [
...
'attachment_id',
...
]
public function attachment(): HasOne{
return $this->hasOne(ProjectAttachment::class, foreignKey: 'id', localKey: 'attachment_id');
}
protected $fillable = [
...
'attachment_id',
...
]
public function attachment(): HasOne{
return $this->hasOne(ProjectAttachment::class, foreignKey: 'id', localKey: 'attachment_id');
}
and in ProjectResource class, I am using
Section::make('Attachment')
->relationship('attachment')
->columns(2)
->schema([
Select::make('type')
->options(ProjectAttachmentType::options())
->native(false)
->reactive()
->required(),
TextInput::make('url')
->label('URL')
->url()
])
Section::make('Attachment')
->relationship('attachment')
->columns(2)
->schema([
Select::make('type')
->options(ProjectAttachmentType::options())
->native(false)
->reactive()
->required(),
TextInput::make('url')
->label('URL')
->url()
])
Although I was very confident it will work, this is only adding rows in ProjectAttachment table and not updating the attachment_id in Project table when submitting a create record request, resulting into empty columns in Attachment section above. But if I add attachment_id manually in database, it would fill up the columns in Attachment. Can someone please help with if I missed anything?
Solution:
You are right, Thanks you fixed the issue, I am sorry that the parameters had me confused. In hasOne relationship, foreign_key is actually supposed to be parent's id column in child entity, which in my case would be project_id (or no need to mention as you said). I thought I would only need the project_id column in belongsTo relation because it would save me a column. Now I removed attachment_id because its no longer in use.
Jump to solution
4 Replies
Dan Harrin
Dan Harrin7mo ago
this isnt what they are asking for?
gladjanus43
gladjanus437mo ago
I know, was changing my comment 🥲
Dan Harrin
Dan Harrin7mo ago
i might be wrong, but are you sure your foreignKey and localKey definitions are the right way round? isnt the foreign key supposed to be the non-primary key, so attachment_id? and i dont think you need to define the local key
Solution
Amitoj
Amitoj7mo ago
You are right, Thanks you fixed the issue, I am sorry that the parameters had me confused. In hasOne relationship, foreign_key is actually supposed to be parent's id column in child entity, which in my case would be project_id (or no need to mention as you said). I thought I would only need the project_id column in belongsTo relation because it would save me a column. Now I removed attachment_id because its no longer in use.
Want results from more Discord servers?
Add your server