php - 错误 : Integrity constraint violation: 1052 when Join in Laravel Eloquent

标签 php mysql laravel

我试图通过指定它们的关系(即外键和本地键)并使用 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)功能显示($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)并将其用作过滤器。但是,由于连接,此字段不明确。

要解决这个问题,您可以手动添加过滤器:

$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();

关于php - 错误 : Integrity constraint violation: 1052 when Join in Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54923946/

相关文章:

php - 使用 phpredis-ubuntu 12.04

mysql - 我可以从 MySQL 分区中受益吗?

php - 如何在 PHP 中自动发布到 google plus?

php - 从 Wordpress 中的摘录中剥离标签不起作用

php - Ajax 片段元标记 - Googlebot 未读取页面内容

mysql - 乘以列值

具有所有列的mysql查询加上对某一列的计数

php - csv 未使用 laravel 上传到数据库

laravel - 在 Laravel 中动态编辑 config/database.php 文件

php - Laravel 5.2 - 如何返回 PDF 作为 JSON 响应的一部分