首页 > 解决方案 > 没有密钥的 Laravel 雄辩关系

问题描述

我如何渴望在 eloquent 中加载另一个模型?这种关系并不完全是传统意义上的关系,而是一种要求。

我有一张users桌子,一张target_types桌子。每个user人都会有一样的target_types。因此,表target_types中存在的任何内容都target_types将适用于所有users. 所以不需要外键类型的关系。

我意识到我可以沿着查询构建器路线走,但理想情况下我希望能够执行以下操作:

User::with('target_types')->get();

有任何想法吗?

标签: phplaraveleloquentrelationship

解决方案


正如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.

推荐阅读