Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel关系多对多不正确的返回计数_Php_Laravel_Eloquent - Fatal编程技术网

Php Laravel关系多对多不正确的返回计数

Php Laravel关系多对多不正确的返回计数,php,laravel,eloquent,Php,Laravel,Eloquent,我有一个适用于培训师和学生的用户模型。在我的业务逻辑培训师中,学生被分配到某个单元,因此我在他们之间建立了多对多关系 public function students() { return $this->belongsToMany(User::class, 'trainer_student', 'trainer_id','student_id'); } public function trainers() { return $this->belo

我有一个适用于培训师和学生的用户模型。在我的业务逻辑培训师中,学生被分配到某个单元,因此我在他们之间建立了多对多关系

public function students()
{
    return $this->belongsToMany(User::class, 'trainer_student',  
    'trainer_id','student_id');
}

    public function trainers()
{
    return $this->belongsToMany(User::class, 'trainer_student','student_id', 'trainer_id');
}
两者都在用户模型中。我检查了DB,有8名学生与某个单元的培训师有关

所以我用Tinker做了这个查询:

$trainer = User::findOrFail(21);
$trainer->students()->pluck('id');

但如果我像往常一样提问:

DB::table('trainer_student')->where('trainer_id',21)->pluck('student_id')

发生了什么事?为什么这种关系显示出的学生较少?我做错了什么


谢谢

我认为这些专栏对你们的关系来说是倒退的。首先尝试学生id,然后尝试培训师id。
student\u trainer
将遵循雄辩的命名约定,但是,通过
trainer\u student
正确提供数据透视表名称,因此这不会有什么区别。
$trainer->students()->toSql()
的结果是什么,您可能应该这样做:
User::with('students')->findOrFail(21)以加载这些学生。是否有外键限制?您确定数据库中存在这些用户吗?我看到它们存在于联接表中,但是在用户表中呢?