Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic properties

后端 未结 1 824
终归单人心
终归单人心 2021-01-05 15:47

I am trying to model a pretty straightforward relationship, between the \'Users\' table and the \'User_profiles\' table. Each user has a user_profile, so it\'s a simple one-

相关标签:
1条回答
  • 2021-01-05 16:04

    Ok so the problem had to do with using underscores in the class names. Laravel follows PSR 0 and 1 as outlined here.

    What this means is I had to name my model class and filename UserProfile (even though my MySql table named remained 'user_profiles'), and then update my User model to have a function called userProfile().

    Once I updated the naming, I could access the relationships automatically by doing something like:

    $user = Auth::user();
    echo $user->userProfile->first_name;
    
    0 讨论(0)
提交回复
热议问题