'Column not found: 1054 Unknown column when submitting form with subfield relationship
This issue happens for me on Backpack v5 and Laravel 8 (although I do reproduce it on Laravel 9 as well).
My issue happens when I have a setup similar to this one : https://backpackforlaravel.com/docs/5.x/crud-fields#manage-related-entries-in-the-same-form-create-update-delete
Just to clarify here:
- Two models related by a 1-n relationship
- Those models override their
$primaryKeyattribute (as their primary key is not "id") - the "parent" models CRUD that has a
'type' => 'relationship'with'subfields'to add children through a "repeatable" type field
This is the error I get (with the Monsters and Stories example):
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id_story' in 'where clause'
select * from `monsters` where `monsters`.`story_id` = 5 and `monsters`.`story_id` is not null and (`id_story` is null) limit 1
The stack trace leads me to vendor\backpack\crud\src\app\Library\CrudPanel\Traits\Create.php:310
Here is how I reproduced it on the Backpack demo projet:
Install demo project following instructions here :https://backpackforlaravel.com/docs/4.1/demo#demo-installation
Rename
monstersprimary key in table toid_monsterandstoriesprimary key toid_storyAdd the
$primaryKeyoverrides on corresponding models like so:protected $primaryKey = 'id_monster'; // In Monster.php protected $primaryKey = 'id_story'; // In Story.phpAdd correct "foreignKey" parameters to relation method like so:
// In Story.php public function monsters() { return $this->hasMany(\App\Models\Monster::class, 'story_id'); } // In Monster.php public function story() { return $this->belongsTo(\App\Models\Story::class, 'story_id'); }
Now add a story with a monster through the Crud panel and you should reproduce the error.
I'm thinking I'm probably missing something but I just can't figure it out. I'm pretty sure the relations are properly defined and I'm wondering if it's not a bug in Backpack.
Thanks for your help !
UPDATE
This is indeed an issue that has been reported here
Solution 1:[1]
I'm seeing that you are using "story_id" in both relations (Story.php and Monster.php).
In Story.php you should use :
public function monsters()
{
return $this->hasMany(\App\Models\Monster::class, 'story_id');
}
And In Monster.php you should use :
public function story()
{
return $this->belongsTo(\App\Models\Story::class, 'monster_id');
}
Also be careful that when you are trying to set relationships in migrations and in models, you are setting correct foreign keys both in migration and models.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mojtaba Michael |
