dpl74687
2015-07-28 18:46
浏览 123
已采纳

Laravel中hasMany和belongsToMany之间的关系

I have two Models - InternalNotesThread and InternalNotes

class InternalNotesThread extends Model {

public function notes(){

        return $this->hasMany('App\InternalNotes', 'thread_id', 'id');
    }
}

class InternalNotes extends Model {

public function thread() {

        return $this->belongsTo('App\InternalNotesThread');
    }
public function users()
    {
        return $this->belongsToMany('App\User', 'user_notes_tagged', 'internal_notes_id', 'user_id');
    }
}

Also, InternalNotes is mapped to User with a relation of belongsToMany.

DB Structure:

internal_notes_thread:
id - int
ticket_id (FK) - int
name - string

internal_notes:
id - int
thread_id (FK) - int
notes - string

user_notes_tagged: (Many to many with internal_notes and User)
internal_notes_id (FK) - int
user_id (FK) - int

For every note, there might be some user tagged in it.

How can I directly relate this relationship with the internal_notes_thread???

I get the data with this:

$data = InternalNotesThread::with('notes')->where('ticket_id', '=', $id)->get()->toArray();

But, in the notes array, I am not able to get the users tagged in that note

How can I get all the data in one go???

图片转代码服务由CSDN问答提供 功能建议

我有两个模型 - InternalNotesThread和InternalNotes

 类InternalNotesThread  extends Model {
 
公共函数notes(){
 
返回$ this-> hasMany('app \ InternalNotes','thread_id','id'); 
} 
} 
 
class InternalNotes  extends Model {
 
公共函数thread(){
 
返回$ this-> belongsTo('App \ InternalNotesThread'); 
} 
公共函数用户()
 {
返回$ this-&gt  ; belongsToMany('App \ User','user_notes_tagged','internal_notes_id','user_id'); 
} 
} 
   
 
 

此外,还会映射InternalNotes 与belongsToMany关系的用户。

数据库结构:

  internal_notes_thread:
id  -  int 
ticket_id(FK) -  int 
name  -  string 
 
internal_notes:  
id  -  int 
thread_id(FK) -  int 
notes  -  string 
 
user_notes_tagged :(内部注释和用户多对多)
internal_notes_id(FK) -  int 
user_id(FK) -  int 
  <  / pre> 
 
 

对于每个音符,可能会有一些用户标记。

如何直接将此关系与internal_notes_thread相关联?

我得到的数据是这样的:

  $ data = InternalNotesThread :: with('notes') - &gt; where('ticket_id',  '=',$ id) - &gt; get() - &gt; toArray(); 
   
 
 

但是,在 notes 数组中 ,我无法在该笔记中标记用户

如何一次性获取所有数据?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drwxg62286 2015-07-28 19:01
    已采纳

    You're not eager loading the users, so they don't show up in your ->toArray() array.

    Try this:

    $data = InternalNotesThread::with('notes.users')
        ->where('ticket_id', '=', $id)
        ->get()
        ->toArray();
    
    点赞 评论

相关推荐 更多相似问题