我正在尝试从用户组织中选择一个“网站” . 我可以通过使用成功检索用户组织(作为组织对象)

$user->organisation

但是当我尝试使用以下方法检索属于该组织的网站时:

$user->organisation->sites

我将我的数据库中的每个站点都返回(作为集合) .

我的用户模型的组织关系:

public function organisation()
{
    return $this->belongsTo('App\Models\Organisation', 'organisation_id');
}

我的组织模型的用户和站点关系:

public function users()
{
    return $this->hasMany('App\Models\User');
}

public function sites()
{
    return $this->hasMany('App\Models\Site');
}

我的网站模型的组织关系:

public function organisation()
{
    return $this->belongsTo('App\Models\Organisation');
}

User Table

  • id

  • organisation_id

  • 名字

  • 电子邮件

  • 密码

  • last_login

  • persist_code

  • reset_password_code

  • remember_token

  • created_at

  • updated_at

  • deleted_at

  • 负责_to

Organisations

  • id

  • 名字

  • created_at

  • updated_at

  • deleted_at

Sites

  • id

  • organisation_id

  • 名字

  • 地址

  • account_code

  • created_at

  • updated_at

  • deleted_at

我已经包含了我认为在这里有用的所有内容,但我错过了任何我会按要求添加它的内容 .

我有以下解决方法,但我仍然不满意上述原因不能按预期工作 .

$organisation = Organisation::where('id', $user->organisation->id)->first();
$site = Site::where('organisation_id', $organisation->id)->first();

上面的解决方法从我的表中返回第一个真正与我的用户模型 Build 关系的站点 .

如果我删除 ->first() ,我会通过组织获得与我的用户关联的网站集合,而不是表格中的所有网站 .

谢谢