我的代码
$result=DB::table('receipts')
->join('dealer_m','receipts.ToDealerID','dealer_m.DealerID')
->join('dealer_m','receipts.FromDealerID','dealer_m.DealerID')
->join('product_m','receipts.ProductID','product_m.ProductID')->get();
餐桌收据
Id | FromDealerId | ToDealerId | ProductId
---+---------------+-------------+------------
1 1 2 1
2 1 3 1
3 3 1 1
桌子经销商_m
DealerId | DealerName
---------+-----------
1 Dealer One
2 Dealer Two
3 Dealer Three
表product_m
ProductId | ProductName
----------+-----------
1 Product One
2 Product Two
预期产量
Id | FromDealerId | ToDealerId | ProductId | FromDealerName | ToDealerName | ProductName
---+---------------+-------------+------------+----------------+--------------+------------
1 1 2 1 Dealer One Dealer Two Product One
2 1 3 1 Dealer One Dealer Three Product One
3 3 1 1 Dealer Three Dealer One Product One
我运行代码时出现错误
SQLSTATE [42000]:语法错误或访问冲突:1066不是唯一的 表/别名:'dealer_m'(SQL:从'receipts'内部联接中选择' '收据'上的'dealer_m'。'ToDealerID'='dealer_m'。'DealerID'内部 在'receipts'上加入'dealer_m'。'FromDealerID'='dealer_m'。'DealerID' 内部联接'收据'上的'product_m'。'ProductID'= 'product_m'。'ProductID')
如何解决这个问题?
谢谢
答案 0 :(得分:1)
$results=DB::table('receipts')
->select('receipts.*','dealer_m1.DealerName as ToDealer','dealer_m2.DealerName as FromDealer','product_m.ProductName')
->join('dealer_m as dealer1','receipts.ToDealerID','dealer_m.DealerID')
->join('dealer_m as dealer2','receipts.FromDealerID','dealer_m.DealerID')
->join('product_m','receipts.ProductID','product_m.ProductID')->get();
您只需要给每个联接表一个别名
现在在您的刀片中:
@foreach ($results as $result)
<tr>
<td>{{$result->Id}}</td>
<td>{{$result->FromDealerId}}</td>
<td>{{$result->ToDealerId}}</td>
<td>{{$result->ProductId}}</td>
<td>{{$result->FromDealer}}</td>
<td>{{$result->ToDealer}}</td>
<td>{{$result->ProductName}}</td>
</tr>
@endforeach
当然,如果您卡在刀片中调用什么,只需打印我们的集合以找到键=>值或执行dd($ results);在控制器中进行检查,然后再进入视图。
答案 1 :(得分:0)
您应该尝试以下操作:
$result=DB::table('receipts')
->join('dealer_m as dealer_id','receipts.ToDealerID','dealer_m.DealerID')
->join('dealer_m as dealer_f_id','receipts.FromDealerID','dealer_m.DealerID')
->join('dealer_m as product_p_id','receipts.ProductID','product_m.ProductID')->get();