1

I am making user and address table. That would be one to one relationship. When I see some examples of company and user one to one relationship, company had a foreign key and user had no key assigned. How is it decideD?

Company table

  $table->integer('user_id')->unsigned()->nullable();
  $table->foreign('user_id')->references('id')->on('users');
Jassica
  • 143
  • 1
  • 9

1 Answers1

0

I have take the example in laravel docs to explain your problem:

For example, a User model might be associated with one Phone. To define this relationship, we place a phone method on the User model. The phone method should call the hasOne method and return its result:

Class User {
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

then we can get phone that belong to user :

$phone = User::find(1)->phone;

Eloquent determines the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key.

So, we can access the Phone model from our User. Now, let's define a relationship on the Phone model that will let us access the User that owns the phone.

class Phone 
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Here is a representation of tables :

___________                    __________
| User    |                    | Phone   |
|_________|                    |_________|
| id      |                    |   id    |
|_________|                    |_________|
| name    |                    | number  |
|_________|                    |_________|
| lastname|                    | user_id | ----------> foreign key 
|_________|                    |_________|
bruno
  • 128
  • 1
  • 3