我正在尝试从数据透视表中获取数据(我有第三列)。但它返回空数组。当我做dd()时我得到了这个
Collection {#323 ▼
#items: []
}
$a = new Subject();
$authorized_users = $a->users()->get(['auth_teacher']);
模型
主题
public function users()
{
return $this->belongsToMany('App\User')->withPivot('auth_teacher')->withTimestamps();
}
用户
public function subjects()
{
return $this->belongsToMany('App\Subject')->withPivot('auth_teacher')->withTimestamps();
}
编辑:错误编写的列名。我将其更改为正确但字符串仍为空
答案 0 :(得分:3)
只需在模型上使用pivot
关系。
$a = Subject::find(1);
foreach ($a->users as $user) {
echo $user->pivot->auth_teacher;
}
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
在文档中查找"检索中间表列"
答案 1 :(得分:0)
尝试以下代码:
$a = new Subject();
$authorized_users = $a->users()->find(['subject_id']);