【问题标题】:Relationship between a hasMany and belongsToMany in LaravelLaravel 中 hasMany 和 belongsToMany 之间的关系
【发布时间】:2015-07-29 03:01:47
【问题描述】:

我有两个模型 - InternalNotesThread 和 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');
    }
}

此外,InternalNotes 映射到 User 的关系为 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: (Many to many with internal_notes and User)
internal_notes_id (FK) - int
user_id (FK) - int

对于每条笔记,都可能有一些用户被标记在其中。

我怎样才能直接将这种关系与 internal_notes_thread 联系起来???

我用这个得到数据:

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

但是,在 notes 数组中,我无法获取在该便笺中标记的用户

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

【问题讨论】:

  • 抱歉,拼写错误。已编辑。

标签: php laravel laravel-5


【解决方案1】:

您并不急于加载用户,因此他们不会出现在您的 ->toArray() 数组中。

试试这个:

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

【讨论】:

  • 像魅力一样工作!谢谢!
  • 如果我只想从 User 表中获取 user_id 怎么办。目前它向我显示了所有字段。
  • 见laravel.com/docs/5.1/…——类似->with('notes.users' => function ($query) { $query->select(['id']); })
  • 是的,我知道这一点。但是,在这种情况下它不起作用。
  • 发布一个关于这个的新问题并附上一些细节,我会看看是否能提供帮助。
猜你喜欢
  • 2021-03-22
  • 2018-01-03
  • 2021-10-07
  • 2022-01-16
  • 2014-12-30
  • 2019-10-01
  • 2018-05-19
  • 2016-07-12
  • 2021-12-14
相关资源
最近更新 更多