使用grocery-crud关联id_ab失败,需提取Subname与Expire
Hey there, let's figure out why your Grocery CRUD relation isn't working and get you the Subname and Expire fields you need!
What's Going Wrong
Looking at your code and table structure, a few issues are likely causing the relation to fail:
- Incorrect relation logic: The
set_relationmethod expects the first parameter to be the foreign key in your main table, but your setup haslista_ab.id_abas the primary key, andlista_ab_term.id_abas the foreign key linking back to it. Your current call doesn't align with this relationship properly. - Missing primary keys: Neither of your tables has a primary key defined in the CREATE statements. Grocery CRUD relies on primary keys to handle relations correctly.
- Unspecified display columns: You haven't told Grocery CRUD which fields to show, so even if the relation worked, you wouldn't see
SubnameandExpireby default.
Step-by-Step Fix
1. Add Primary Keys to Your Tables
First, let's fix the database structure by adding primary keys (this is critical for Grocery CRUD to function):
ALTER TABLE `lista_ab` ADD PRIMARY KEY (`id_ab`); ALTER TABLE `lista_ab_term` ADD PRIMARY KEY (`ID`);
2. Update Your Grocery CRUD Code
Adjust your code to correctly define the relation and specify the fields you want to extract:
$crud->set_table('lista_ab'); // Link the main table's id_ab to the related table's id_ab, and display the Expire field $crud->set_relation('id_ab', 'lista_ab_term', 'Expire'); // Explicitly set the columns you want to show: Subname from lista_ab, Expire from lista_ab_term $crud->columns('Subname', 'Expire');
If you're working with a one-to-many relationship (one lista_ab entry has multiple lista_ab_term entries), you might need to use set_relation_n_n or adjust how you fetch the data, but for a one-to-one match, the above code should work perfectly.
If you also want these fields to appear in the add/edit forms, add this line:
$crud->fields('Subname', 'Expire');
Quick Checks to Verify
- Make sure there are matching
id_abvalues in both tables (the relation only works when the values align). - Double-check that you're using a recent version of Grocery CRUD to avoid any outdated bugs.
内容的提问来源于stack exchange,提问作者Dobi Caps

