当连接第二个字段并且第一个忽略时,2个表具有相同的字段名称

时间:2015-05-10 22:26:55

标签: laravel laravel-4 laravel-5

我有2个表,两者都有created_at字段,当连接2个表时,结果返回第二个表的created_at。

我正在使用laravel 5.

我的查询:

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(['*']);

如何为收据和交易返回created_at。

2 个答案:

答案 0 :(得分:3)

您应该使用别名:

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

按照你的例子:

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();

答案 1 :(得分:1)

我通常只得到我需要的字段。

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'
            ]);