【问题标题】:Error: Integrity constraint violation: 1052 when Join in Laravel Eloquent错误:完整性约束违规:在 Laravel Eloquent 中加入时出现 1052
【发布时间】:2019-07-22 06:22:12
【问题描述】:

我试图通过指定它们的关系(即外键和本地键)并使用 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)",

这是根据选择显示的功能 公共功能展示($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 表 我需要在 votes.user_id = users.id 上加入 votes 和 users 表

public function index()
        {
            $votes = auth()->user()->votes;

            return response()->json([
                'success' => true,
                'data' => $votes
            ]);
        }

谢谢

【问题讨论】:

标签: php mysql laravel


【解决方案1】:

这是因为您正在使用->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();

【讨论】:

  • 谢谢,显示错误:“stdClass 类的对象无法转换为字符串”
  • 它在抱怨 $vote = auth()->user()->$dbconnect;错误:stdClass 类的对象无法转换为字符串
  • 那行没有意义。你想达到什么目的?
  • 我正在尝试确保用户已通过身份验证。 $vote - auth()-user()
  • 当我删除它时,它显示一个错误:调用未定义的方法 stdClass::toArray()。代码中的这一行“'data' => $vote->toArray()”
猜你喜欢
  • 2012-12-26
  • 2021-12-13
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 2020-10-13
  • 2019-04-14
相关资源
最近更新 更多