使用查询构建器联接从多个表中获取唯一值

时间:2017-10-18 10:30:57

标签: php sql laravel laravel-5.4

我能够查看所有已连接的表值,但问题是它是重复的。我已经在我的控制器中使用了distinct。

我想显示交易的产品,数量和trans_amount。

Table View

控制器:

$products = DB::table('transactions')
        ->join('transactions_prods', 'transactions_prods.trans_id', '=', 'transactions.id')
        ->join('products', 'products.id', '=', 'transactions_prods.prod_id')
        ->join('users', 'users.id', '=', 'transactions.user_id')
        ->join('transactions_solds', 'transactions_solds.trans_id', '=', 'transactions.id')
        ->select('transactions_prods.prod_id as id', 
                 'transactions.type as Type', 
                 'products.prod_name as product_name', 
                 'transactions_prods.qty as qty',
                 'transactions.id as transid',
                 'users.id as user_id',
                 'transactions_solds.trans_amt as amount')
        ->where('transactions.type', '=', 'Sell')
        ->where('transactions.id', '=', $id)
        ->distinct()->get();

        return view('system.transactions.edit_transaction')->with('products', $products);

edit_transactions.blade.php

       <div class="panel-heading"><b>TransID: {{$products[0]->transid}}</b>
        <br>
        <b>CashierID: {{$products[0]->user_id}}</b>
    </div>

    <div class="panel-body" style="overflow-x:auto;">

        <table id="data-table" class="table table-hover">
            <thead>
                <tr>
                    <th valign="middle">ID</th>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Amt</th>
                    <th>Action</th>

                </tr>
            </thead>
            <tbody>
                @foreach($products as $product)
                    <tr>
                        <td>{{$product->id}}</td>
                        <td>{{$product->product_name}}</td>
                        <td>{{$product->qty}}</td>
                        <td>{{$product->amount}}</td>
                        <td>
                            <a href="#" class="btn btn-sm btn-danger">REMOVE</a>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>

表:

transactions
id | type | user_id

transactions_prods
id | trans_id | prod_id| qty

transactions_solds
id | trans_id | trans_amt | trans_scd

users
id | name | role_id | email | password

2 个答案:

答案 0 :(得分:1)

这里的问题可能是加入users表。根据您想要的结果,这似乎没有必要。

答案 1 :(得分:0)

我已经解决了这个问题。谢谢你的支持。我将prod_id和qty合并到transactions_solds表中并使用了distinct。