I have a User model, and an Item model. Each Item has one Category, and each User has a "benlongsToMany" relationship to Category that determines what Items they should see. To select all items that a user can see, I do this:
$items = Item::whereIn('category_id', function($query) use ($user) {
$query->select('category_id')->from('user_category')->where('user_id', '=', $user->id);
})->orderBy('title')->get();
This works, however hard-coding the table and field names for the relationship table seems like bad practice. Is there a better Eloquent way of doing this? Just by pseudocode, something like
$items = Item::whereIn(Item->category->local_id, function($query) use ($user) {
$query->select(User->categories->foreighn_id)->from(User-categories->pivot_table_name)->where(User->categories->local_ld, '=', $user->id);
})->orderBy('title')->get();
Is it possible to access the field/table names of the relationships in the query?
Hi, i am on my phone so i cant go into Detail, but you should look up "Working with pivots" and Eloquent relationships in the laravel docs.
I think you will find what you are looking for.
Good luck.
Sure you can:
$item = new Item;
$items = $item->whereIn($item->category()->getForeignKey(), function($query) use ($user) {
$query->select($user->categories()->getOtherKey())
->from($user->categories()->getTable())
->where($user->categories()->getForeignKey(), '=', $user->getKey());
})->orderBy('title')->get();
Ah, exactly what I was looking for, thank you!
I did read the documentation but it didn't specify how to get the local/foreign key from what I could find, and I guess I was just bad at reading the API docs. Feels a lot better to not have to mix hard-coded column and table names, kind of defeats a large part of Eloquents purpose :). I'll try it out.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community