[英]Laravel Eloquent Relationship without key
How do I eager load another model in eloquent? 我如何渴望雄辩地加载另一个模型? The relationship isn't exactly a relationship in the traditional sense, it's a requirement.
关系不是传统意义上的关系,而是必须的。
I have a users
table, and a target_types
table. 我有一个
users
表和一个target_types
表。 Every user
will have all of the same target_types
. 每个
user
将具有所有相同的target_types
。 So whatever target_types
are present in the target_types
table, will apply to all users
. 所以,无论
target_types
存在于target_types
表,将适用于所有users
。 So there's no need for a foreign key type of relationship. 因此,不需要外键类型的关系。
I realise I could go down the query builder route, however ideally I'd love to be able to do something like: 我意识到我可以沿查询生成器路线走,但是理想情况下,我希望能够执行以下操作:
User::with('target_types')->get();
Any ideas? 有任何想法吗?
As Felippe Duarte suggested, you could just return to your view/API both collections: $users
and $targetTypes
. 正如Felippe Duarte所建议的那样,您只需将两个集合都返回到view / API:
$users
和$targetTypes
。
app/Http/Controllers/SomeCoolController.php 应用程序/ HTTP /控制器/ 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]);
}
You say that the targetTypes
will be the same for all users. 您说所有用户的
targetTypes
都相同。 In case this types doesn't change very often. 以防这种类型不经常更改。 Why not store them inside the model?
为什么不将它们存储在模型中?
app/User.php 应用程序/ user.php的
public function getTargetTypesAttribute()
{
return ['my', 'list', 'of, 'target', 'types'];
}
Then you could use it when querying for your users: 然后,您可以在查询用户时使用它:
$user = User::first();
dd($user->target_types);
// this will output the list of target types.
You can 'fake' the relationship in the user model like this: 您可以像这样在用户模型中“伪造”关系:
//in User model
public function targetTypes(){
return TargetType::where("deleted_at", "<>", "NULL");
}
Then you can call it with the user in the controller like so: 然后,您可以在控制器中与用户一起调用它,如下所示:
User::with('targetTypes')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.