Laravel 完整性约束违规:1052 where 子句中的列“id”不明确

我在访问关系时遇到问题。语法如下:


$student = \App\StudentRegistrars::find($id);


        foreach($student->father_registrars as $getFatherData) {

            $fatherID = $getFatherData->id;

            $specificFather = \App\FatherRegistrars::where('id', $fatherID);

            $specificFather->update(['status' => 'Pending']);


            //count qualified students who have father with id $fatherID

            //problem lays here

            $getSelectedStudent = \App\StudentRegistrars::where('status', 'Qualified')->whereHas('father_registrars', function($q) use($fatherID) {

                $q->where('id', $fatherID);

            })->count();

            if($getSelectedFather == 1) {

                $fatherUsername = $getFatherData->username;

                $fatherCredential = \App\User::where('username', $fatherUsername);

                if($fatherCredential) {

                    $fatherCredential->forceDelete(); 

                }

            }

        }

父亲注册员


public function student_registrars(){ 

        return $this->belongsToMany('App\StudentRegistrars')->withTrashed();

    }

学生注册员


public function father_registrars(){

        return $this->belongsToMany('App\FatherRegistrars')->withTrashed(); 

    }

用户


class User extends Authenticatable implements MustVerifyEmail

    use Notifiable;

    use HasRoles; //spatie

    use SoftDeletes; //trash user


    /** 

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'name', 'username', 'gender', 'phone', 'email', 'password',

    ]; 


更新: 我会更清楚地解释这个案例。我的意思是,有一个父母带着他的两个孩子,如下图所示:

http://img3.mukewang.com/6496c82d0001982f06500130.jpg

当我点击“合格”按钮时,它将users自动在表中生成帐户,如下图所示:

http://img3.mukewang.com/6496c83d0001437c06510212.jpg

小唯快跑啊
浏览 156回答 2
2回答

蛊毒传说

//count qualified students who have father with id $fatherID//problem lays here$getSelectedStudent = \App\StudentRegistrars::where('status', 'Qualified')->whereHas('father_registrars', function($q) use($fatherID) {                $q->where('id', $fatherID);            })->count();在$q->where('id', $fatherID);这里,“id”不明确,因为在您的连接查询中,表father_registrars和student_registrars表都具有相同的列id。因此,在您的情况下,没有表名的条件是导致不明确的原因。指定表名和列将解决您的问题。所以在你的情况下,你的查询应该是这样的。$getSelectedStudent = \App\StudentRegistrars::where('status', 'Qualified')->whereHas('father_registrars', function($q) use($fatherID) {                    $q->where('father_registrars.id', $fatherID);                })->count();

杨__羊羊

在您正在执行的第一个 foreach 循环中...$specificFather = \App\FatherRegistrars::where('id', $fatherID);当你应该做类似的事情时$specificFather = \App\FatherRegistrars::where('id', $fatherID)->first();或者$specificFather = \App\FatherRegistrars::findOrFail($fatherID);同样在第二个 foreach 中...$fatherCredential = \App\User::where('username', $fatherUsername)->first();
打开App,查看更多内容
随时随地看视频慕课网APP