отношения между 5 таблицами - PullRequest
0 голосов
/ 22 декабря 2018

У меня есть 5 таблиц «Пользователь», «Профиль», «Адрес», «Штат», «Город». Требуется создать связь между таблицами. У адреса есть идентификатор штата, идентификатор города и идентификатор профиля в таблице. В таблице указан идентификатор пользователя в таблице.в таблице.Как записать отношения между таблицей

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

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


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

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

class Profile extends Model
{
    public function address() {
        return $this->belongsTo('App\Address');
    }
    public function user() {
        return $this->belongsTo('App\User');
    }
}

class Address extends Model
{
    public function profile() {
        return $this->belongsTo('App\Profile');
    }
    public function city() {
        return $this->belongsTo('App\City');
    }
    public function state() {
        return $this->belongsTo('App\State');
    }

}

// users table
public function profile(){
    return $this->hasOne('App\Profile');
}

Ответы [ 2 ]

0 голосов
/ 23 декабря 2018

как @ mustafa.akcoban говорит ...

Когда вы используете ownTo, Eloquent будет работать следующим образом

$this->belongsTo('App\City', 'foreign_key', 'other_key');
// foreign_key = is the primary key in the related model, by default 'id' for Eloquent 
// other_key = is the field in the current model that contains the id of the other model, by default othermodelname_id for Eloquent
// For eg. 'App\City', 'id', 'city_id' 

При использовании hasMany Eloquent работает следующим образом

$this->hasMany('App\Model', 'currentmodel_id', 'primary_key');
// currentmodel_id = is the field that contains the current model primary key in the related model
// primary_key = is the current primary key model that will be in the other model, by default id for Eloquent
// For eg. 'App\City', 'state_id', 'id' 

Помните, что вы можете или не можете использовать второй и третий параметр, если что-то не так, дамп Laravel сообщит вам, какой столбец не был найден в таблице, и вы сможете это исправить.

Пожалуйста, попробуйте на практике, и дайте мне знать, как это работает :)

0 голосов
/ 22 декабря 2018

Как правило, дизайн вашей модели верный, я отредактировал несколько частей.Попробуйте коды ниже.

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

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


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

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

class Profile extends Model
{
     public function addresses() 
     {
         return $this->hasMany('App\Address');
     }

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

class Address extends Model
{
      public function profile() 
      {
           return $this->belongsTo('App\Profile');
      }

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

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

class User extends Model
{
     public function profile()
     {
          return $this->hasOne('App\Profile');
     }
}

Кстати, , отношения Laravel добавляют ключи по умолчанию в соответствии с именами ваших методов.Если у вас есть проблема, вы можете найти информацию из официальных документов.Например:

$ this-> ownTo ('App \ Model', 'foreign_key', 'other_key');

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...