Bruno Francisco
Bruno Francisco

Reputation: 4240

belongsTo not returning results as desired

I would like to a user be able to only have one distrito (it means district in Portuguese). A distritocan have more than one user. It's a fairly simple relationship but the problem comes when you have a third table called distritosthat it's only job is to translate numbers into strings (I don't know the name of such tables).

Distrito table

$table->increments('id');
$table->string('distrito');

e.g.

ID  DISTRITO
1 - Aveiro
2 - Beja
3 - ...

User tables

$table->string('name');
$table->string('last_name');
$table->string('profile_picture')->default('default.jpg');
$table->string('userProfile')->default('');
$table->float('stars')->default(0);

distrito_user table this table will reference where the user live

$table->integer('user_id'); //id of the user
$table->integer('distrito_id');  //Id of the district where the user lives

User's model

public function distritoUtilizador(){
    return $this->belongsTo(DistritoUser::class);
}

DistritoUser's model

protected $table = 'distrito_user';

Calling the eloquent model

$user = Auth::user();
dd($user->distritoUtilizador);

It returns null.

First question: Is this the correct way to solve my problem (the user lives somewhere and I need to fill that location)?

If this is the right way to solve my problem: Why it's not returning the desired results?

Upvotes: 0

Views: 74

Answers (1)

user320487
user320487

Reputation:

For a simple one to many, just store the foreign key to distrito on the user model, no need for intermediate tables.

$table->increments('id')->unsigned();
$table->string('name');
$table->string('last_name');
$table->string('profile_picture')->default('default.jpg');
$table->string('userProfile')->default('');
$table->float('stars')->default(0);
$table->integer('distrito_id')->unsigned();
$table->foreign('distrito_id')->references('id')->on('distrito');

and get rid of the distrito_user table altogether. now use has this method:

public function distrito(){
    return $this->belongsTo(Distrito::class, 'id');
}

while distrito has:

public function users(){
    return $this->hasMany(User::class);
}

also change distrito migration to:

$table->increments('id')->unsigned();

Upvotes: 1

Related Questions