![](/img/trans.png)
[英]SQLSTATE[23000]: Integrity constraint violation: 1052. Laravel eloquent issue when joining table
[英]Error: Integrity constraint violation: 1052 when Join in Laravel Eloquent
我試圖通過指定它們的關系(即外鍵和本地鍵)並使用 find(id) 將兩個表連接在一起。 從頭開始,我使用了 where 和 get()。 它沒有給出同樣的錯誤然后我注釋掉了 where 子句以使用 find($id)
"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select `votes`.`flavour`, `users`.`email` from `votes` inner join `users` on `votes`.`user_id` = `users`.`id` and `id` = 1 limit 1)",
這是基於選擇顯示的函數 public function show($id) {
$dbconnect = DB::table('votes')
->join('users', 'votes.user_id', '=', 'users.id')
//->where('votes.id', $id)
->select('votes.id','votes.date_of_birth','votes.voter_ip','votes.flavour', 'users.email')
->find($id);
$vote = auth()->user()->$dbconnect;
if (!$vote) {
return response()->json([
'success' => false,
'message' => 'Vote with id ' . $id . ' not found'
], 400);
}
return response()->json([
'success' => true,
'data' => $vote->toArray()
], 400);
}
全部顯示:在這個函數中,我也應該使用 join,但我只使用了它准確顯示的投票表 我需要在 votes.user_id = users.id 上加入投票和用戶表
public function index()
{
$votes = auth()->user()->votes;
return response()->json([
'success' => true,
'data' => $votes
]);
}
謝謝
這是因為您正在使用->find($id)
函數。 此函數將查找模型的主鍵(在本例中為id
)並將其用作過濾器。 但是,由於join,這個字段是有歧義的。
要解決此問題,您可以手動添加過濾器:
$dbconnect = DB::table('votes')
->join('users', 'votes.user_id', '=', 'users.id')
->select('votes.id','votes.date_of_birth','votes.voter_ip','votes.flavour', 'users.email')
->where('votes.id', $id)
->first();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.