Cannot get belongsTo relationship field to display #443
-
I have two models: Office and OfficeCategory. Office belongs to OfficeCategory and OfficeCategory has many Offices. class Office extends Model
{
public function category(): BelongsTo
{
return $this->belongsTo(OfficeCategory::class);
}
} class OfficeCategory extends Model
{
public function offices(): HasMany
{
return $this->hasMany(Office::class);
}
} In the OfficeCrudController, when attempting to list offices, the Category column doesn't display the Category name, it simply displays the category id, or a dash (depending on which field type I attept). protected function setupListOperation()
{
CRUD::column('name');
CRUD::column('user_id')->label('User')->type('select')->entity('User')->attribute('name')->model('App\Models\User');
$this->crud->addColumn([
// 1-n relationship
'label' => 'Category', // Table column heading
'type' => 'select',
'name' => 'office_category_id', // the column that contains the ID of that connected entity;
'entity' => 'category', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => "App\Models\OfficeCategory", // foreign key model
]);
if (!$this->crud->getRequest()->has('order')) {
//CRUD::orderBy('position');
//CRUD::positionColumn();
$this->crud->orderBy('lft', 'asc'); // set the default order by position
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @WhiskeyM1ke from what I see, everything is correct in that code sample you provided. The example you want to implement is exactly the same as the package NewsCRUD provides, you can see the demo here; Do you have the Make use of |
Beta Was this translation helpful? Give feedback.
Hi @WhiskeyM1ke from what I see, everything is correct in that code sample you provided.
The issue may be somewhere else.
The example you want to implement is exactly the same as the package NewsCRUD provides, you can see the demo here;
https://demo.backpackforlaravel.com/admin/article
Do you have the
name
attribute on OfficeCategory?Make use of
php artisan tinker
to test your models and relations 👌