简体   繁体   中英

Laravel eloquent extending model

I have default user model. Now I have another table for Administrators. Is there a way to return user fields (since admin is extending user) from admin model ? I found this example but its when admin_id is present in user model. I have one-to-one relation here.

class Admin extends User
{
    protected $table = 'users';

    public static function boot()
    {
        parent::boot();

        static::addGlobalScope(function ($query) {
            $query->where('is_admin', true);
        });
    }
}

This is the example I found. I'm not sure how can I return user fields from my admin model when its on different table.

The point is I want to be able to do something like this (call methods from users):

Admin::first()->posts()

Where posts method is not on Admin class but on user class.

Edit:

To explain it better. I have two tables, users and admins. They are connected in one-to-one relationship so I can do something like this:

$admin = Admin::first();
$posts = $admin->user()->posts();

but since Admin should have all fields from users table and one more field from admins table I'm looking for a way to do this:

$admin = Admin::first();
$posts = $admin->posts();

I don't want to add admin or something to users table, I still want to use admins table since I will need more fields there later.

If both tables have an equal id, use a trait to define your relationships:

trait UserRelationships {
    public function posts() {
         return $this->hasMany(Post::class, 'user_id');
    }
}

class Admin {
    use UserRelationships;
}

class User {
    use UserRelationships;
}

You'll just have to be sure to explicitly declare the foreign key name in the relationship.

You could also extend the User model and override the $table property but this may present problems for various reasons since User properties exist on the user relationship and not on the Admin 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