2015-09-21 76 views
0

我试图获取阅读特定杂志的用户的ID列表。Laravel belongsToMany and Eloquent查询

事情表(杂志)

id 
name 

thing_progresses

id 
progress_value 

thingprogress_thing

id 
thing_progress_id (FK from thing_progresses table) 
thing_id (FK from things table) 
user_id (FK from users table) 

事情型号

namespace App\Models; 
use Illuminate\Database\Eloquent\Model; 

class Thing extends Model 
{ 
    public function readers() { 
     return $this->belongsToMany('\App\Models\ThingProgress', 'thingprogress_thing'); 
    } 
} 

我的应用程序

$readers = Thing::with(array('readers' => function($query) use ($id) { 
$query->where('thing_progress_id', '1'); 
}))->find($id); 

查看

@foreach($readers as $reader) 
    {{$reader->user_id}} 
@endforeach 

这里是我的错误。

Trying to get property of non-object (View: /Applications/MAMP/htdocs/master/resources/views/frontend/thing/book/index.blade.php) 
+0

您倾销了'$ readers'吗?它是集合还是单个对象? – BrokenBinary

回答

0

要获取属性是一个数据透视表(并且不是FK的关系),您必须告诉Laravel获取它们。

只需添加withPivot('user_id')的关系,即

public function readers() { 
    return $this->belongsToMany('\App\Models\ThingProgress', 'thingprogress_thing')->withPivot('user_id'); 
} 

然后,您可以用访问:

$reader->pivot->user_id 

希望这有助于!