yajra / laravel-datatables-buttons

Laravel DataTables Buttons Plugin
https://yajrabox.com/docs/laravel-datatables/buttons-installation
MIT License
254 stars 53 forks source link

getColumns() function fails when relation name is camel-cased #128

Closed djamesfar closed 2 years ago

djamesfar commented 3 years ago

getColumns() does not recognize camel-cased relation names

Using implementation in infyom/laravel-generator, I have a quotes table with several simple belongsTo relations to other tables. One is named in camel-cased convention: quoteStatus, relating to the quote_statuses table using a foreign key quote_status_id. Datatables returned no data if I included `'defaultContent' => '', and an error if I removed this (relation not found).

Code snippet of problem

from QuoteDataTables:

protected function getColumns()
    {
        return [
            'quote_date',
            'number',
            'quoteStatus' => new Column([
                'title' => 'Quote Status',
                'name' => 'quoteStatus.name',
                'data' => 'quoteStatus.name',
                'defaultContent' => '',
            ]),
// the following, and all other non-camel-case relations, works:
            [
                'title' => 'Customer',
                'data' => 'customer.full_name',
                'name' => 'customer.full_name',
                'defaultContent' => '',
            ],
            ...

from Quote model (relation method in camel-case):

class Quote extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     **/
    public function quoteStatus()
    {
        return $this->belongsTo(\App\Models\QuoteStatus::class, 'quote_status_id');
    }

after changing Quote model relation name to slug case (works):

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     **/
    public function quote_status()
    {
        return $this->belongsTo(\App\Models\QuoteStatus::class, 'quote_status_id');
    }

and changing getColumns() (works):

    protected function getColumns()
    {
        return [
            'quote_date',
            'number',
            'quote_status' => new Column([
                'title' => 'Quote Status',
                'name' => 'quote_status.name',
                'data' => 'quote_status.name',
                'defaultContent' => '',
            ]),
            ...

System details

yajra commented 3 years ago

This is a laravel behavior when serializing the model to array. Your column should be something like this:

'name' => 'quoteStatus.name',
'data' => 'quote_status.name',

Related docs: https://datatables.yajrabox.com/eloquent/relationships https://yajrabox.com/docs/laravel-datatables/master/relationships