soulbork's avatar

Lazy load not replacing existing properties

I have a Game model with the following relations:

    public function game_type()
    {
        return $this->belongsTo(GameType::class, 'game_type_id');
    }

    public function admin()
    {
        return $this->belongsTo(User::class, 'admin');
    }

When I lazy load using $game->load(['admin', 'game_type']);, I get the following object:

admin: {id: 11, first_name: null, last_name: null,  …}
game_type: {id: 4, name: null, description: null}
game_type_id: 4

Lazy load replaces the admin field with the entire admin model, which is what I want. However it adds a game_type model instead of replacing the game_type_id field, which I don't want.

It works perfectly if I rename the game_type_id field to just game_type and adjust the relation to:

    public function game_type()
    {
        return $this->belongsTo(GameType::class, 'game_type');
    }

However this feels somewhat 'hacky' and doesn't follow the naming conventions of my database. Is there a way to get lazy loading to replace the game_type_id field instead of adding a new attribute without renaming my database?

0 likes
2 replies
kevinbui's avatar
kevinbui
Best Answer
Level 41

Having the game_type_id field is correct and conforming to the general convention. I will be puzzled when the relationship and the table field having the same name like that admin relationship.

In this example, I suggest renaming this admin field to be admin_id. There's nothing wrong with having the game_type_id and admin_id fields.

If you don't want those fields, pls use resources, or simply do this:

$game->load(['admin', 'game_type']);

unset($game->admin_id);
unset($game->game_type_id);

return $game;
1 like

Please or to participate in this conversation.