数据透视表返回空数组

时间:2016-12-06 13:19:53

标签: php laravel laravel-5 eloquent laravel-5.2

我正在尝试从数据透视表中获取数据(我有第三列)。但它返回空数组。当我做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();
}   
编辑:错误编写的列名。我将其更改为正确但字符串仍为空

2 个答案:

答案 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']);