简体   繁体   中英

Best way for Eloquent Model inheritance in Laravel 5?

I have a Laravel project and I'm using Eloquent for models.

Let's say I have three related tables:

User
Demographics
Roles

I would like my User model to inherit both Demographics and Roles based on Foreign Key as a one-to-one relation.

I am just looking for some feedback on what might be the most efficient / elegant / safest / performant / cleanest way to accomplish this.

So you're just looking for basic relations and eager loading those relations.
Try this:

class User extends Model
{
    public function demographic()
    {
        return $this->hasOne('App\Demographic');
    }
    public function role()
    {
        return $this->hasOne('App\Role');
    }
}
class Demographic extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
class Role extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Then to access the User with all relations:

$user = User::with(['demographic', 'role'])->find(1);

var_dump($user->demographic); // returns the related Demographic model
var_dump($user->role); // returns the related Role model

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