2016-04-06 156 views
0

我正在通过关于egar加载的Laracasts视频工作,迄今为止这么好!我怎样才能从渴望的加载中加入表值?

我以为我很好地理解了这些概念,但现在我已经习惯了如何使用它(CodeIgniter)和这种非常棒的方式。

我有3个表:

cards  #card_id, title, created_at, updated_at 
notes  #note_id, name, created_at, updated_at 
card_notes #card_id, note_id 

card_notes有FK字段:

card_id #FK back to cards->card_id 
note_id #FK back to notes->note_id 

我能够得到所有笔记给定的卡:

CardsController.php

public function show(Card $card) 
{ 
    $card->load('notes'); 
} 

Card.php

public function notes() 
{ 
    return $this->hasMany(CardNote::class); 
} 

JSON

{ 
    id: 1, 
    title: "First Card", 
    created_at: null, 
    updated_at: null, 
    notes: [ 
     { 
      card_id: 1, 
      note_id: 1, 
      created_at: null, 
      updated_at: null 
     }, 
     { 
      card_id: 1, 
      note_id: 2, 
      created_at: null, 
      updated_at: null 
     } 
    ]    
} 

到目前为止,一切都很好! 现在,在我的notes表中,我有一个name列我想要显示。这是我卡住的地方。我能找到我的查找表,但我还没有想出如何获得过去该表并进入连接表。它看起来像我需要hasManyThrough但是......我落在我的脸上。

return $this->hasManyThrough(Note::class, CardNote::class); 

我需要获取给定note_id所有笔记记录,但我不知道如何下钻到旁边的水平。这就是我想在年底产生:

JSON

{ 
    id: 1, 
    title: "First Card", 
    created_at: null, 
    updated_at: null, 
    notes: [ 
     { 
      card_id: 1, 
      note_id: 1, 
      name: "John Doe" 
      created_at: null, 
      updated_at: null 
     }, 
     { 
      card_id: 1, 
      note_id: 2, 
      name: "Jane Doe" 
      created_at: null, 
      updated_at: null 
     } 
    ]    
} 

谢谢你的任何建议!

回答

0

如果你继续滚动,结果会有所帮助。我知道我与hasManyThrough接近,我只是错过了可选参数。

return $this->hasManyThrough(Note::class, CardNote::class, 'card_id', 'note_id');