简体   繁体   中英

Extending models in Laravel Eloquent

In my application I have a User (duh)

class User {

    public function teams()
    {
        return $this->belongsToMany(Team::class, 'team_user', 'user_id')->wherePivot('confirmed', '!=', null);
    }
}

Im trying to make a model that extends the User , like so

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

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

        static::addGlobalScope(new TeamleaderScope);
    }
}

The idea is that a team leader is a user that has the isLeader boolean in the team_user pivot table set to true. In my TeamleaderScope I've tried something like

class TeamleaderScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $model->teams()->wherePivot('isLeader', true);
    }
}

but that seems to be wrong, cause Teamleader::all( ) just returns all the users. I've never tried extending a model like this, but it should be possible, right? Can anyone help me in the right direction?

for reuse the common method and etc in the two class in PHP, you can use the trait . in your case, create a php file in next to the rest of the models and I named it CommonTrait.php and inside it must like below:

<?php

namespace App;


trait CommonTrait
{
    public function commonMethodOne()
    {
        // anything
    }

    public function commonMethodTwo()
    {
        // anything
    }

    // for get leaders.
    public function scopeLeaders()
    {
        return $this->teams()->wherePivot('isLeader', true);
    }

    public function scopeSearchLeaders($query, $keyword)
    {
         return $query->where('name', $keyword)->wherePivot('isLeader', true);
    }


}

so now you use trait anywhere that you want.

for example, use it in the User.php :

<?php

namespace App;

class User
{
    use CommonTrait;
}

so, now all method or variable in CommonTrait.php accessible in the User.php and you capable using the those in the User.php and you can use it in the Teamleader.php and using all method it in the Teamleader.php .
for example, now if you want to get users that are team leaders, you can try followings code:

$leaders = User::Leaders();
$resultSearch = User::SearchLeaders("Gard Mikael");

I hope be useful

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