yajra / laravel-datatables

jQuery DataTables API for Laravel
https://yajrabox.com/docs/laravel-datatables
MIT License
4.76k stars 859 forks source link

Handling Null relationships when used as service #1358

Closed longestdrive closed 10 months ago

longestdrive commented 7 years ago

Hi I'm using this as a service. I can get it working for basic tables but now experimenting with relationships.

I've successfully displayed the name of a relationship but I get errors where the relationship is empty as it's expecting a value to exist.

I'm not sure how to handle this - should I modify the column? should I modify the query - confused!

Here is the query and column definition:

It works fine when a relationship exists as the data contains the relation parent_category and I can then access the child object.

When the relationship does not exist I get this datatables error: equested unknown parameter 'parent_category.name' for row 7, column 1.

public function query()
    {
        $categories = categories::query()->with('parent_category');

        return $this->applyScopes($categories);
    }

private function getColumns()
    {
        return [
            'name' => ['name' => 'name', 'data' => 'name'],
            'Parent' => ['name' => 'parent_category.name', 'data' => 'parent_category.name'],
            'rule' => ['name' => 'rule', 'data' => 'rule']
        ];
    }

I have tried modifying the ajax call to this but the added column makes not difference - even if I remove the 'Parent' column in the getColumns() function above.

public function ajax()
    {
        return $this->datatables
            ->eloquent($this->query())
            ->addColumn('Parent', function (categories $category) {
                return $category->parent_category ? str_limit($category->parent_category->name, 30, '...') : 'null';
            })
            ->addColumn('action', 'categories.datatables_actions')
            ->make(true);
    }

System details

Laravel 5.4 using homestead VM Using version 6 of laravel-datatables to maintain compatibility with another package InfyOm Labs laravel-generator

lk77 commented 7 years ago

i think you should use a left join instead, this way you will get empty values.

yajra commented 7 years ago

I think the problem here is on the scripts. You are calling the data from parent_category.name and should be Parent.

private function getColumns()
    {
        return [
            'name' => ['name' => 'name', 'data' => 'name'],
            'Parent' => ['name' => 'parent_category.name'],
            'rule' => ['name' => 'rule', 'data' => 'rule']
        ];
    }
github-actions[bot] commented 10 months ago

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] commented 10 months ago

This issue was closed because it has been inactive for 7 days since being marked as stale.