简体   繁体   中英

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. Every user will have all of the same target_types . So whatever target_types are present in the target_types table, will apply to all 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 .

app/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]);

}

Alternative

You say that the targetTypes will be the same for all users. In case this types doesn't change very often. Why not store them inside the model?

app/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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM