php - 没有密钥的 Laravel 雄辩关系
问题描述
我如何渴望在 eloquent 中加载另一个模型?这种关系并不完全是传统意义上的关系,而是一种要求。
我有一张users
桌子,一张target_types
桌子。每个user
人都会有一样的target_types
。因此,表target_types
中存在的任何内容都target_types
将适用于所有users
. 所以不需要外键类型的关系。
我意识到我可以沿着查询构建器路线走,但理想情况下我希望能够执行以下操作:
User::with('target_types')->get();
有任何想法吗?
解决方案
正如Felippe Duarte建议的那样,您可以返回到您的视图/API 两个集合:$users
和$targetTypes
.
应用程序/Http/Controllers/SomeCoolController.php
public function index(Request $request)
{
// get your users
$users = User::all();
// get your target types
$targetTypes = TargetType::all();
// return them to your front-end
return response([
'data' => [
'users' => $users,
'target_types' => $targetTypes
]
], 200);
// or in case you have a view
// return view('my_cool_view', ['users' => $users, 'targetTypes' => $targetTypes]);
}
选择
你说这targetTypes
对所有用户都是一样的。如果这种类型不经常改变。为什么不将它们存储在模型中?
应用程序/用户.php
public function getTargetTypesAttribute()
{
return ['my', 'list', 'of, 'target', 'types'];
}
然后您可以在查询用户时使用它:
$user = User::first();
dd($user->target_types);
// this will output the list of target types.
推荐阅读
- java - string.split() 方法的输出
- python - 循环输出不会产生单独的行
- r - 有没有办法让这个 R 代码更有效率?
- validation - 使用 map reduce 在数据集中进行地址验证
- mysql - 如何为每个 id 获取一些数据的结果?
- python - 如何在tensorflow中将一片占位符张量添加到1?
- java - Java 模式停留在简单的正则表达式模式
- python - AttributeError:模块“simplejson”在“导入烧瓶”上没有属性“转储”
- asp.net-mvc - 如何连接两个表之间的多对多关系的相关数据?
- javascript - 如何阻止提交按钮刷新?