简体   繁体   中英

Getting pivot table information within controller Laravel 5.4

my tables: 在此处输入图片说明

I have the following controller:

 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); } 

Basically in $id - i have id of the user. $user variable should get group_id of that user and use that id in findOrFail function to retrieve group information.

Relationships:

 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'); } } 

Your relationships are ok.

I think your logic is not well because it's considering just one group for the user, but a user could have many groups.

You should consider retrieve all groups first then perform the rest of the logic.

$groups = App\User::find(1)->group()->get()->toArray();
$groups = array_column($groups, 'group');
$files = App\Files::select('urls')->whereIn('group_id', $groups);

Edit.

Your group relationship in the User model doesn't have a return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM