Laravel访问HasMany关系模型的BelongsTo

时间:2018-07-23 11:49:15

标签: php laravel eloquent

基本上,我有3个模型,Wedding,邀请和用户。婚礼有邀请,而邀请有用户(请记住,该用户可以属于多个邀请)。我想直接访问$wedding->users

Wedding.php

class Wedding extends Model
{

  public function invites()
  {
     return $this->hasMany(Invite::class);
  }
...

Invites.php

class Invite extends Model
{

  public function user()
  {
     return $this->belongsTo(User::class);
  }
...

表格:

Wedding
- id
- name

Invite
- invite_date
- wedding_id
- user_id

User
- id
- name
- email

我想使用$wedding->users直接访问检索用户 婚礼和用户之间有什么关系?

2 个答案:

答案 0 :(得分:0)

将此方法添加到Widding类中

// initialize:
var indices = source.Copy();
// add values:
indices.AddRange(otherDictionary);

有关public function users() { return $this->hasManyThrough('App\User', 'App\Invite'); } 的更多信息,请参见documentation

答案 1 :(得分:0)

这是BelongsToMany关系:

public function users() {
    return $this->belongsToMany(User::class, 'invites');
}