The Larable is very flexible in this regard, as the database already existed and consequently did not follow the same nomenclature of Laravel
, there are ways to pass the key names in the settings, examples:
Relationship 1:1
A person has an address and an address belongs to a person:
class Peoples extends Model
{
//Relacionamento.
public function address()
{
// $this->hasOne(relacao, chave estrangeira, primary key);
return $this->hasOne('App\Address', 'peopleid', 'id');
}
}
class Address extends Model
{
//Relacionamento.
public function people()
{
// $this->belongsTo(relação, chave estrangeira local, primary key da relação);
return $this->belongsTo('App\Peoples', 'peopleid', 'id');
}
}
Relationship 1:N
A person may have one or more phones:
class Peoples extends Model
{
//Relacionamento
public function phones()
{
// $this->hasMany(relação, chave estrangeira da relação, primary key local);
return $this->hasMany('App\Phones', 'peopleid', 'id');
}
}
class Phones extends Model
{
//Relacionamento
public function people()
{
// $this->belongsTo(relação, chave estrangeira local, primary key da relação);
return $this->belongsTo('App\Peoples', 'peopleid', 'id');
}
}
Relationship N:M
An author may have several books and a book may have several authors, where this relation generates an intermediate table.
class Authors extends Model
{
//Relacionamento.
public function books()
{
// $this->belongsToMany('relacao',
// 'nome da tabela pivot',
// 'key ref. authors em pivot',
// 'key ref. books em pivot')
return $this->belongsToMany('App\Books',
'booksauthors',
'authorid',
'bookid');
}
}
class Books extends Model
{
//Relacionamento.
public function authors()
{
// $this->belongsToMany('relacao',
// 'nome da tabela pivot',
// 'key ref. books em pivot',
// 'key ref. author em pivot')
return $this->belongsToMany('App\Authors',
'booksauthors',
'bookid',
'authorid');
}
}
These are the most traditional relationships (perhaps suffering some variation to some bank model) and can help you adjust your old bank, but beyond those three there are some other types described in the documentation which can also be observed.
I’ve also written some answers that you can use as a basis:
References
Adriano, and then gave a clear answer?
– novic
Siiimm!! Thank you very much. I understood what you said, I will try to apply. Thank you
– Adriano Vianna
If it’s useful to you take it as an answer!
– novic