Laravel属于ToMany和Eloquent查询

时间:2015-09-21 18:34:22

标签: eloquent laravel-5.1

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

  事物表(杂志)

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)

1 个答案:

答案 0 :(得分:0)

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

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

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

然后您可以使用以下方式访问它:

$reader->pivot->user_id

希望这有帮助!