lundi 19 mars 2018

Laravel - Model BelongsTo multiple models

I am developing a system and I have a question, in the system I have 3 main models (User, State, City), to manage the users I use a package for Laravel called Entrust, with this package I can define system roles, one of these roles is the manager, the manager can have Cities and States, however, a States can have several Cities, so in my model Cities BelongsTo to a User and a States.

Is that correct? A model can BelongsTo more then one model? I found no satisfactory answer on Google.

User.php

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;
    use SearchableTrait;

    protected $fillable = [
        'role',
        'active',
        'status',
        'name',
        'slug',
        'email',
        'password',
        'cpf',
        'rg',
        'mothers_name',
        'marital_status',
        'curriculum',
        'psychiatric_report',
        'contract',
        'phone',
        'adress',
        'city',
        'state',
        'country',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $searchable = [
        'columns' => [
            'users.name' => 10,
            'users.slug' => 8,
            'users.email' => 8,
        ]
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function states()
    {
        return $this->hasMany('App\State');
    }

    public function cities()
    {
        return $this->hasMany('App\City');
    }
}

State.php

class State extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'initials',
        'manager_id'
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function manager(){
        return $this->belongsTo('App\User');
    }

    public function cities(){
        return $this->hasMany('App\City');
    }
}

City.php

class City extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'state_id',
        'manager_id',
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function manager(){
        return $this->belongsTo('App\User');
    }

    public function state(){
        return $this->belongsTo('App\State');
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2HM9eKA
via IFTTT

Aucun commentaire:

Enregistrer un commentaire