Laravel belongsToMany and Eloquent query



我正在尝试获取阅读特定杂志的用户ID列表。

things table(杂志)

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 AppModels;
use IlluminateDatabaseEloquentModel;
class Thing extends Model
{
    public function readers() {
        return $this->belongsToMany('AppModelsThingProgress', '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)

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

withPivot('user_id')添加到关系中,即

public function readers() {
    return $this->belongsToMany('AppModelsThingProgress', 'thingprogress_thing')->withPivot('user_id');
}

然后你可以使用:

$reader->pivot->user_id

希望这对你有帮助!

最新更新