Ayman Hussein
Ayman Hussein

Reputation: 3857

2 tables has the same field name when join the second field is returned and the first ignore

I have 2 tables and the both have created_at field, when join the 2 tables the result return created_at for the second table.

I am using laravel 5.

my Query:

Receipt::with('paymentMethod')->with('transaction')
                    ->join('transactions', 'receipts.transaction_id', '=', 'transactions.id')
                    ->join('currencies', 'transactions.currency_id', '=', 'currencies.id')
                    ->where('receipts.transaction_id',$id)->get(['*']);

how can i return created_at for receipts and for transaction.

Upvotes: 0

Views: 246

Answers (2)

Moinescu Mihai
Moinescu Mihai

Reputation: 21

I usually get only the fields I need.

Receipt::with('paymentMethod')->with('transaction')
            ->join('transactions', 'receipts.transaction_id', '=', 'transactions.id')
            ->join('currencies', 'transactions.currency_id', '=', 'currencies.id')
            ->where('receipts.transaction_id',$id)
            ->get([
                'receipts.created_at AS receipt_created_at', 
                'transactions.created_at AS transaction_created_at'
            ]);

Upvotes: 1

Fernando Montoya
Fernando Montoya

Reputation: 2644

You should use an alias:

Model::select('transactions.created_at AS t_created_at')->get();

Following your example:

Receipt::with('paymentMethod')->with('transaction')
                    ->join('transactions', 'receipts.transaction_id', '=', 'transactions.id')
                    ->join('currencies', 'transactions.currency_id', '=', 'currencies.id')
                    ->where('receipts.transaction_id',$id)
->select('transactions.created_at AS t_created_at', '...')
->get();

Upvotes: 3

Related Questions