Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Snake Case Model relationships don't appear to work #4307

Closed
c0ntax opened this issue May 2, 2014 · 3 comments
Closed

Snake Case Model relationships don't appear to work #4307

c0ntax opened this issue May 2, 2014 · 3 comments

Comments

@c0ntax
Copy link

c0ntax commented May 2, 2014

I've just come across the following oddness. If I define a Model thusly:

class Person extends \Eloquent
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function posts()
    {
        return $this->hasMany('Person', 'person_id', 'person_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function all_posts()
    {
        return $this->hasMany('Person', 'person_id', 'person_id');
    }
}

When I do the following

var_dump(\Person::find(1)->posts);

I get a collection back. But, if I use the snake-cased all_posts method/var I get a null. E.g.

var_dump(\Person::find(1)->all_posts);

Is this a bug or a feature?

@RyanNielson
Copy link
Contributor

This is the method that's causing the issue you see: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L2249.

Basically what is happening is Eloquent is looking for an attribute called all_posts. Since it doesn't exists, it actually converts all_posts to allPosts and looks up a relationship method with that name instead of with all_posts. I'm not exactly sure why it was done this way, but it was. Also Laravel encourages the use of camelCase method names anyway. A quick glance at the code makes it look like if you had a relationship method named allPosts, you could actually use Person::find(1)->all_posts or Person::find(1)->allPosts to get it. You're getting null because of this line: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L2274

@taylorotwell
Copy link
Member

All methods should be camelCase per PSR-1.

@c0ntax
Copy link
Author

c0ntax commented May 2, 2014

Good to know... Thanks! :-D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants