1

I'm trying to limit the columns retrieved in With function.

The following works:

\App\Models\SalesItems::select('si.id', 'si.sale_id', 'si.total')
    ->from('sales_items AS si')
    ->with('Sale:id,document_id,customer')
    ->get();

This returns:

[
    0: 
    {
        id: 12,
        sale_id: 32,
        total: 92.00
        sale: 
        {
            id: 1,
            document_id: 9,
            customer: 'John',
        }
    }
]

The following does not work:

\App\Models\SalesItems::select('si.id', 'si.sale_id', 'si.total')
    ->from('sales_items AS si')
    ->with('Sale:id,document_id,customer')
    ->with('Sale.Document:id,description')
    ->get();

As it returns:

[
    0: 
    {
        id: 12,
        sale_id: 32,
        total: 92.00
        sale: 
        {
            id: 1,
            document_id: 9,
            customer: 'John',
            employee_id: 2,
            due_date: '2020-03-03',
            preview: false,
            created_at: '2020-03-03 14:04:32',
            updated_at: '2020-03-03 14:04:32',
            document: 
            {
                id: 9,
                description: 'Invoice'
            }
        }
    }
]

Why are the fields employee_id, due_date, etc being called if I didn't ask?

Linesofcode
  • 5,327
  • 13
  • 62
  • 116
  • Check https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent – Mate May 03 '20 at 01:55
  • @Mate I'm aware of that solution, but doesn't work for me. It returns all the columns. – Linesofcode May 03 '20 at 02:00

1 Answers1

0

Because of your second with() loader you have requested all sale columns, that is the reason.

Solution

\App\Models\SalesItems::select('si.id', 'si.sale_id', 'si.total')
    ->from('sales_items AS si')
    ->with([
        'sale' => function ($query) {
            $query->select('id','document_id','customer');
            $query->with('Document:id,description');
        },
    ])
    ->get();
Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28