我有两个表,'用户'和'主题,有自定义数据透视表'讲座_主题',
我正在尝试通过在Subject类中添加以下代码来建立多对多的关系:
function users(){
return $this->belongsToMany('App\User','lecturers_subjects','user_id','subject_id');
}
但是,当我试图为某些主题显示用户时,它找不到用户($ subject->用户数组为空)
$subjects = Subject::all();
foreach($subjects as $subject){
var_dump($subject->id); //displays 1
foreach($subject->users as $user){ //array is empty
var_dump($user->id);
}
}
我错过了什么?
答案 0 :(得分:2)
更改
function users(){
//order of keys
return $this->belongsToMany('App\User','lecturers_subjects','subject_id','user_id');
}
那应该这样做