簡體   English   中英

連接表並找到並獲取指定的行

[英]join table and find and get an specified row laravel

我試圖從聯接表中獲取指定的記錄,我的查詢如下

$user = Auth::user(); //current authenticated user
$user_id = $user->id; //get the current authenticated user's id
$users = DB::table('users') //join table users and table user_details base from matched id;
    ->join('user_details', 'users.id', '=', 'user_details.id')
    ->find($user->id) //find the record matched to the current authenticated user's id from the joint table records
    ->get(); //get the record
dd(var_dump($users)); //dump result

但不幸的是它給了我這個錯誤

SQLSTATE [23000]:完整性約束違規:在where子句是不明確的1052列的'id'(SQL:SELECT * FROM users內部聯接user_detailsusersid = user_detailsid ,其中id = 1個限制1)

所以我敢打賭我的查詢是錯誤的大聲笑! 無論如何,有什么幫助,想法嗎?

由於錯誤本身描述了上表id應該把它放置狀態,所以你需要更換你的findwhere等作為

->where("users.id",$user->id)

代替

->find($user->id)

您應該在user_details表中使用“ user_id”(不僅是“ id”),因為它不知道where子句中的表ID屬於什么。

  1. user_details表中的id更改為user_id
  2. 試試這個: ->join('user_details', 'users.id', '=', 'user_details.user_id')

如果您不想更改數據庫:將->find($user->id)替換為->where("users.id", "=", $user->id)

嘗試以下操作:使用where()方法而不是find()方法。 這將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM