Laravel 5.4 - 如何从自定义中间表模型(数据透视)中获取子数据?

时间:2017-06-13 09:36:17

标签: eloquent laravel-5.4

我有M-M雄辩的关系:会员 - 评论 - 专辑。

成员: ID

专辑: ID

注释: id,member_id,album_id,reply_to,text

评论表中的“reply_to”列包含评论的ID(用于评论回复)

模型

//Member
...
public function comments(){
    return $this->belongsToMany('App\Album', 'comments', 'member_id', 'member_id')->using('App\Comment');
}


//Album
...
public function comments(){
    return $this->belongsToMany('App\Member', 'comments', 'album_id', 'member_id')
    ->withPivot('id', 'reply_to',  'text', 'created_at')
    ->using('App\Comment');
}

//Comment
use Illuminate\Database\Eloquent\Relations\Pivot;
class Comment extends Pivot
...
public function album(){
        return $this->belongsTo('App\Album');
    }

    public function member(){
        return $this->belongsTo('App\Member');
    }
public function scopeChildren(){
        return $this->where('reply_to', $this->id);
    }

以下是我尝试获取评论列表的方法:

@foreach($album->comments as $commenter)
// $commenter->pivot is working
@endforeach

问题是,如何使用上面代码中的scopeChildren()根据“reply_to”获取评论数据? 计数数据正在运行: $commenter->pivot->children()->count()

但是获取数据不起作用: $commenter->pivot->children()->get()

dd($commenter->pivot->children())返回此:

`Builder {#418 ▼
  #query: Builder {#419 ▶}
  #model: Comment {#405 ▶}
  #eagerLoad: []
  #localMacros: []
  #onDelete: null
  #passthru: array:11 [▶]
  #scopes: []
  #removedScopes: []
}`

同样,当调用此方法$commenter->pivot->children()->get()时,它会返回以下消息: 传递给Illuminate \ Database \ Eloquent \ Relations \ Pivot :: __ construct()的参数1必须是Illuminate \ Database \ Eloquent \ Model的实例,给定数组,

0 个答案:

没有答案