Php Laravel 5.0 ORM关系
我正在尝试从用户“组织”中选择一个“站点”。 我可以通过使用成功检索用户的组织(作为组织对象)Php Laravel 5.0 ORM关系,php,laravel,model-view-controller,orm,eloquent,Php,Laravel,Model View Controller,Orm,Eloquent,我正在尝试从用户“组织”中选择一个“站点”。 我可以通过使用成功检索用户的组织(作为组织对象) $user->organisation 但当我尝试使用以下方法检索属于该组织的网站时: $user->organisation->sites 我将数据库中的每个站点都返回(作为集合) 我的用户模型的组织关系: public function organisation() { return $this->belongsTo('App\Models\Organisati
$user->organisation
但当我尝试使用以下方法检索属于该组织的网站时:
$user->organisation->sites
我将数据库中的每个站点都返回(作为集合)
我的用户模型的组织关系:
public function organisation()
{
return $this->belongsTo('App\Models\Organisation', 'organisation_id');
}
public function organisation()
{
return $this->belongsTo('App\Models\Organisation');
}
我的组织模型的用户和站点关系:
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', 'organisation_id');
}
public function organisation()
{
return $this->belongsTo('App\Models\Organisation');
}
用户表
- 身份证
- 机构识别号
- 名字
- 电子邮件
- 密码
- 上次登录
- 持久化代码
- 重置密码密码
- 还记得你的代币吗
- 创建于
- 更新地址
- 删除
- 负责
- 身份证
- 名字
- 创建于
- 更新地址
- 删除
- 身份证
- 机构识别号
- 名字
- 地址
- 账户代码
- 创建于
- 更新地址
- 删除
$organisation = Organisation::where('id', $user->organisation->id)->first();
$site = Site::where('organisation_id', $organisation->id)->first();
上面的解决方法从我的表中返回第一个与我的用户模型真正有关系的站点
如果我删除->first()
,我将获得通过组织与我的用户关联的站点集合,而不是表中的所有站点
谢谢您定义组织可以有更多的站点“公共功能站点(){return$this->hasMany('App\Models\Site');}”这就是您获得集合的原因。抱歉,事实上,我确实希望有一个集合,但只有那些组织id与所讨论的组织匹配的站点,而不是表中的每个站点。请尝试
$user->organization->sites()->get()
谢谢,但我仍然从我的表中获取每个站点。尝试发布数据库的表结构