连接表并查找并获取指定的行laravel

时间:2015-10-09 12:55:26

标签: php mysql laravel laravel-5 eloquent

我试图从连接表中获取指定的记录,我的查询如下

$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]:完整性约束违规:1052 where子句中的列'id'不明确(SQL {select * from users user_details users id user_details }} = idid其中system.netsuite.com = 1限制1)

所以我打赌我的查询错了大声笑!无论如何,任何帮助,想法好吗?

3 个答案:

答案 0 :(得分:3)

由于错误本身描述了哪个表id应该放置条件,因此您需要将find替换为where,如

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

而不是

->find($user->id)

答案 1 :(得分:1)

你应该在user_details表中使用'user_id'(不仅仅是'id'),因为 它不知道where子句中的表id属于什么。

  1. id
  2. 中的user_id更改为user_details
  3. 试试这个:->join('user_details', 'users.id', '=', 'user_details.user_id')
  4. 如果您不想更改数据库: 将->find($user->id)替换为->where("users.id", "=", $user->id)

答案 2 :(得分:0)

尝试以下操作:使用where()方法而不是find()方法。 这将起作用。