我有这些结构的表:(不包括其他列)
am_user:
user_id - 主键
用户名
密码
am_projects:
project_id - 主键
PROJECT_NAME
am_user_project:
USER_ID
PROJECT_ID
我的 用户 模型具有以下关系:
class User extends Authenticatable
{
protected $table = 'am_user';
protected $primaryKey = 'user_id';
public function userproject()
{
return $this->hasMany('App\UserProject', 'user_id', 'user_id');
}
}
我的 UserProject 具有以下关系:
class UserProject extends Model
{
protected $table = 'am_user_project';
protected $primaryKey = null;
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'user_id');
}
public function project()
{
return $this->hasMany('App\Project', 'project_id', 'project_id');
}
}
我的 项目 有这样的关系:
class Project extends Model
{
protected $table = 'am_project';
protected $primaryKey = 'project_id';
public function userproject()
{
return $this->belongsTo('App\UserProject', 'project_id');
}
}
我想列出分配给Authenticated用户的每个项目的所有project_names,我可以从中获取:
public function index() {
$user = User::with(['userproject.project'])->find(Auth::id());
return view('projects', compact('user'));
}
并将其发布到刀片中,如下所示:
<div class="list-group">
@foreach($user->userproject as $userproject)
@foreach($userproject->project as $project)
<a href="#" class="list-group-item"><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> {{ $project->project_name }}</span></a>
@endforeach
@endforeach
</div>
有没有办法真正避免像这样的多个foreach?
答案 0 :(得分:1)
你正在寻找的是一种多任务的关系。请参阅此处的文档:https://laravel.com/docs/5.4/eloquent-relationships#has-many-through
答案 1 :(得分:1)
你必须重新划分你的多对多关系。
删除UserProject模型。
更改用户模型:
class User extends Authenticatable
{
protected $table = 'am_user';
protected $primaryKey = 'user_id';
public function projects()
{
return $this->belongsToMany('App\Project');
}
}
更改项目模型:
class Project extends Model
{
protected $table = 'am_project';
protected $primaryKey = 'project_id';
public function users()
{
return $this->belongsToMany('App\User');
}
}
现在你可以得到这样的用户:
public function index()
{
$user = User::find(Auth::id());
return view('projects', compact('user'));
}
并显示如下:
<div class="list-group">
@foreach($user->projects as $project)
<a href="#" class="list-group-item"><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> {{ $project->project_name }}</span></a>
@endforeach
</div>
了解更多here