在控制器 Laravel 5.4 中获取枢轴 table 信息
Getting pivot table information within controller Laravel 5.4
我的桌子:
我有以下控制器:
public function index($id){
$user = User::find($id)->group()->id;
$group = Group::with('files.urls')->findOrFail($user);
$data ['group'] = $group;
return view('upload.files', $data);
}
基本上在 $id 中 - 我有用户的 ID。 $user 变量应该获取该用户的 group_id 并在 findOrFail 函数中使用该 id 来检索组信息。
关系:
class Group extends Model
{
public function course(){
return $this->belongsTo('App\Course');
}
public function user(){
return $this->belongsToMany('App\User');
}
public function files(){
return $this->hasMany('App\File');
}
}
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'phone'
];
protected $hidden = [
'password', 'remember_token',
];
public function group(){
$this->belongsToMany('App\Group');
}
}
你的人际关系还好。
我认为你的逻辑不太好,因为它只为用户考虑一个组,但一个用户可以有多个组。
您应该考虑先检索所有组,然后再执行其余逻辑。
$groups = App\User::find(1)->group()->get()->toArray();
$groups = array_column($groups, 'group');
$files = App\Files::select('urls')->whereIn('group_id', $groups);
编辑。
您在用户模型中的组关系没有 return。
我的桌子:
我有以下控制器:
public function index($id){
$user = User::find($id)->group()->id;
$group = Group::with('files.urls')->findOrFail($user);
$data ['group'] = $group;
return view('upload.files', $data);
}
基本上在 $id 中 - 我有用户的 ID。 $user 变量应该获取该用户的 group_id 并在 findOrFail 函数中使用该 id 来检索组信息。
关系:
class Group extends Model
{
public function course(){
return $this->belongsTo('App\Course');
}
public function user(){
return $this->belongsToMany('App\User');
}
public function files(){
return $this->hasMany('App\File');
}
}
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'phone'
];
protected $hidden = [
'password', 'remember_token',
];
public function group(){
$this->belongsToMany('App\Group');
}
}
你的人际关系还好。
我认为你的逻辑不太好,因为它只为用户考虑一个组,但一个用户可以有多个组。
您应该考虑先检索所有组,然后再执行其余逻辑。
$groups = App\User::find(1)->group()->get()->toArray();
$groups = array_column($groups, 'group');
$files = App\Files::select('urls')->whereIn('group_id', $groups);
编辑。
您在用户模型中的组关系没有 return。