违反完整性约束:1052 where子句不明确的Laravel

时间:2018-11-11 11:16:30

标签: php laravel laravel-5.2

我想做的事情很简单,运行具有某些关系的查询并为该关系提供where子句。该查询假定要获取具有相关关系的问题,但标签上的where子句只会告诉与已发送的代码($ value)。

userQuestion模型

<?php

namespace App;

class userQuestion extends Model
{
    protected $table = "question";
    public $primaryKey = "question_id";
    protected $fillable = ['question_id'];

    public function gettags() {
        return $this->belongsToMany('App\Profskills','question_profskill',"question_id","prof_id");
    }
}

查询

$allquestions = userQuestion::with('getanswer','getusername','getbounty','gettags')
    ->whereHas('gettags', function($q) use($value) {
        $q->where('prof_id', '=', $value); 
    })
    ->orderBy('created_at','Desc')
    ->get();

问题是它给了我这个错误

 QueryException in Connection.php line 729:
 SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'prof_id' in          
 where clause is ambiguous (SQL: select * from `question` where exists 
 (select * from `prof_skills` inner join `question_profskill` on 
 `prof_skills`.`prof_id` =  `question_profskill`.`prof_id` where `question_profskill`.`question_id` =    `question`.`question_id` and 
 `prof_id` = 1) order by `created_at` desc)

该列存在,并且如果我将该列切换为 qp_id (PrimaryKey),它将起作用,并且来自我试图访问的数据透视表

做了一些谷歌搜索,我所做的是:

在模型中可以用'prof_id'填充的1项(因为我也有数据透视表的模型,做了同样的事情)

2-try => where而不是where

仍然停留,

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在两个表中都有prof_id时,在字段中添加表名。

$allquestions = userQuestion::with('getanswer','getusername','getbounty','gettags')
           ->whereHas('gettags', function($q) use($value) {

       $q->where('question_profskill.prof_id', '=', $value); //question_profskill or prof_skills
})
->orderBy('created_at','Desc')->get();