Many to many relationship: retrieving all items from Table1 with specific value from Table2 I have a many to many relationship: folder_file which lists folder_id and file_id.
What is the proper way to get all the files with specific folder_id? In the following example, I want to retrieve files from folder with id 1, so files with id 1 and 2:
folder_id | file_id
----------|----------
1 | 1
1 | 2
2 | 3
3 | 4
I have the models File and Folder (with corresponding tables files and folders), and relationships set up correctly
You can use the relationship defined in the Folder model.
public function files()
{
return $this->belongsToMany(App\Models\File::class);
}
...
$folder = Folder::find($folder_id);
$files = $folder->files;
@vincent15000 Oh I have to get the folder first.
I thought I could do something similar to this (Though couldn't find the right syntax):
$files = Auth::user()->with('files')->where('folder_id', '=', 1)->get();
or
$files = Auth::user()->files()->wherePivot('folder_id', '=', 1)->get();
though I get certain errors, for example Unknown column 'pivot' in 'where clause' because I guess it completely wrong
Is there something in this style?
@Ligonsker
$files = Auth::user()->with(['files' => function ($query) {
$query->where('folder_id', 1);
})->get();
If you need to have the folder id value dynamically, you need to declare it to be used in the closure.
$folder_id = 1;
$files = Auth::user()->with(['files' => function ($query) use ($folder_id) {
$query->where('folder_id', $folder_id);
})->get();
@vincent15000
It is not working in this case because it looks for the folder_id in the files table, not the folder_file pivot table and I get the same error I was getting before, that folder_id column is not found
@Ligonsker Oh that's true, sorry.
Have you tried by replacing where with wherePivot ?
@vincent15000 yes but I get Unknown column 'pivot' in 'where clause'
@Ligonsker Can you show the relationship in the model ?
Assuming the relationship is User hasMany file
Example:
auth()->user()->load(['files.folder'=>fn($query)=>
$query->where('folder_id',1)->whereIn('file_id',[1,2]);
]);
Please sign in or create an account to participate in this conversation.