2016-12-06 105 views
1

我想从数据透视表中获取数据(我有第三列)。但它返回空数组。当我做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

我不明白为什么你想从'Subject'模型获取一个'subject_id',可以你请妥善阐述你的问题! –

+0

这里我纠正它(它不subject_id是auth_teacher – OunknownO

回答

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

在本文档中查找“检索中间表列”

+0

不,我想从数据透视表中获得第三栏(有键3定制布尔列。我需要第三个)。我知道怎么去具体用户或主题(我写错了列名) – OunknownO

0

试试下面的代码:

$a = new Subject(); 
$authorized_users = $a->users()->find(['subject_id']);