datatables, join same table?

Hellooo i am using a datatable with laravel and I have the following doubt …

$query = DB::table('categories')->select('id','name','parent_id')->orderBy('id');

I have this code that returns me all the categories …
columns: [
        { data: 'id' },
        { data: 'image',
      render: function ( data, type, row ) {
        return data ? '<img src="/images/product/'+data+'" height="80" width="80">' : '<img src="/images/product/noproduct.jpg" height="80" width="80">'; 
 
      }
    },
        { data: 'name' }, // used for sorting so will hide this column
        { data: 'parent_id'}
      ],

And this other code that shows me a datatable with the categories but here the dilemma enters, how do I so that in parent_id instead of showing the ID … it shows the name, should I join the same table? but in none that shows the name of the parent_id

EDIT:The same thing always happens to me, I post and find the solution at the moment, but now another question arose.

$query = DB::table('categories as c')->join('categories as k','c.parent_id','=','k.id')->select('c.id','c.name','k.name as namex')->orderBy('id');

This the correct way?

It have a fail… the categories without parent_id… not appear how can solve it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Just use a leftJoin so records without parent_id will be fetched too, otherwise, records will be restricted to have a parent

$query = DB::table('categories as c')
            ->leftJoin('categories as k','c.parent_id','=','k.id')
            ->select('c.id','c.name','k.name as namex')
            ->orderBy('id');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x