laravel - Eloquent relations from multiple joined tables
问题描述
Let's say we have a table users
and we are left joining multiple tables to it.
$users = User::query()
->select('users.id', 'bananas.id as banana_id', 'dogs.id as dog_id')
->leftJoin('bananas', 'banana.user_id', '=', 'users.id')
->unionAll($usersWithDogs) // a similar query with a left join on `dogs`
->orderByDesc('users.created_at')
->paginate(...);
We end up with a collection of User
models with attributes id
, dog_id
, banana_id
.
Now imagine we want to eager load these, but the eloquent relations are based on the one to many relationships, $user->dogs
, $user->bananas
.
Trying to find a solution that will do all the following:
a) not break pagination
b) allow ordering on the user table
c) allow eager loading
d) use clean code
e) end up with a collection of users
Brainstorming so far has led to the following options:
- A union of
bananas
anddogs
, eager load theuser
relation, then invert the collection (messy code) - Dynamic relationships created on
User
, possibly with a macro on\Illuminate\Database\Eloquent\Builder
. Maybe by leveragingModel::resolveRelationUsing()
- Manual eager loading with a union select with a left join to each table in each arm of the union, then a
whereIn()
to get the related records - Restructure the relations so that there is a polymorphic many to many relationship between users and other entities e.g.
user_id | model_type | model_id
1 | App\Models\Banana | 2
1 | App\Models\Dog | 5
Maybe I'm missing something obvious...?
解决方案
推荐阅读
- android - 运行cordova-android App时显示“等待模拟器启动...”
- php - 致命错误:未捕获的异常“Alchemy\BinaryDriver\Exception\ExecutableNotFoundException”,消息“未找到可执行文件,建议
- c# - 在 Xamarin Forms 中“重新添加”TabbedPage 子项时如何禁用 BottomNavigationView 移位模式?
- javascript - 如何在已部署的应用程序中使用 puppeteer-core 抓取动态网页?
- github - GitHub 组织过滤存储库按非归档
- java - 从java中的arraylist中消除重复值
- python-3.x - 在 python 中逐行读取二进制文件会导致 unicode 数据出现问题吗?
- android - SQLite 数据库项目在重新启动 Activity 后返回,即使它已被删除
- python - 检查一列中的值是否在Python中另一列的区间值中
- sql - 在 ASP.Net MVC Model 类中编写 SQL Query