Merge rows from relation

Merge rows from relation

stepgrstepgr Posts: 13Questions: 3Answers: 0

Hi ,

I'm using laravel 8 & datatables . I have a page that returns companies with contacts. like that:

Company | Contact | Address1 | Address 2 | Phone 1| Phone 2 | Phone 3 | Fax | email

My detail table has separate fields for Name LastName & Location that I want to display under Contact

I Can successfully display a single value from the contacts table using :

{
                data: 'contact.name',
                name: 'contact.name',
                defaultContent: "<i>Not set</i>"
}

The data returned is the following (single row) :

"data":[
{"id":7,"company":"Angels","contactid":17,"address1":"","address2":"","phone1":" 812 3122323","phone2":"","phone3":"","fax":"","email":"op@test.com","created_at":null,"updated_at":null,
"contact":[{"id":31,"idagnt":17,"name":"TBA","lastname":"","place":"","phone":null,"email":null,"remarks":"","created_at":null,"updated_at":null}],

But when I try to merge the rows with something like this :

    {
                    data: 'contact',
                    render: function(data, type, row) {
                         return data.name + ' ' + data.lastname;
                     },
                    defaultContent: "<i>Not set</i>"
                },
    }

I don't get any data back (processing message) , I have tried numerous variations other times I get undefined
other times object Object using the examples in the docs .

I don't know what else to try , maybe someone with more experience can point me at the right direction ?

thanks

Replies

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    Looks like contact is an array. If you want to display all the possible contacts in the array you will need to loop through all the array elements to build the contact list for display. For example:

    render: function(data, type, row) {
        var output = [];
        data.forEach(function ( contact ) {
            output.push( contact.name + ' ' + contact.lastname );
        });
        return output.join( '</br>' );
    },
    

    Didn't test this but it should be close.

    Kevin

  • stepgrstepgr Posts: 13Questions: 3Answers: 0

    Thanks ,
    this is not working also.
    You gave a direction though, one of the problems is that some of these contacts
    are null so first I need to bypass the nulls giving
    defaultContent: "<i>Not set</i>"

  • stepgrstepgr Posts: 13Questions: 3Answers: 0

    Thanks ,

    I figured it out finally , this works :

     data: 'contact',
             render: function(data, type, row) {
                 if (data == null) {
                       return "<i>Not set</i>"
                  }
                  return data.name + ' ' + data.lastname + '</br>' + data.place;
               },
    

    Thank you

Sign In or Register to comment.