2015-09-21 77 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 

希望這有助於!