Laravel One To One Eloquent Relationships

Laravel One To One Eloquent Relationships with ExampleFrom Scratch is today’s leading topic. Laravel is famously known as an Eloquent
ORM
which is Object-Relational Mapper. In this tutorial, we will see how One To One Relationship in Laravel 5.5
is working with an example. So come along with me.

Content Overview

  • 2
    Laravel One To One Eloquent Relationships

    • 3.1
      Step 1: Make one schema for account details.

    • 3.2
      Step 2: Fill the tables with the values.

    • 3.3
      Step 3: Define one to one relationship.

    • 3.4
      An Inverse Of The Relationship.



Prerequisites


If you are new in Laravel 5.5 Eloquent Relationships
, then check out my
Laravel Eloquent Relationships Tutorial

article in this blog.



Laravel One To One Eloquent Relationships


A one-to-one relationship
is a fundamental relation. For example, User model has only one Bank Account, so he has just one account number. So we can connect both models User and Bank as a one to one relationship with each other.
We can place account
method into User
model class, and that account
belongs to only one User
. So in the User
model
, we can call account
method and that one call hasOne
method.



Example


We are defining the one to one relationship with Bank and User. So first we need to set their schema.



Step 1: Make one schema for account details.


Go to the terminal and type the following command.

php artisan make:migration create_accounts_table

So, it will create one schema
file in which, we need to define the columns like the following.

increments('id');
            $table->integer('user_id');
            $table->integer('account_number');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('accounts');
    }
}

Now, fire the following command in the terminal.

php artisan migrate

It will create the tables in the MySQL database.



Step 2: Fill the tables with the values.


We need to fill two tables.

Related Posts

Webpack 3 Tutorial From Scratch


Aug 17, 2017

Callback in Javascript


Apr 18, 2017

  1. users
  2. accounts

Type the following two commands in your terminal.

php artisan make:seeder UsersTableSeeder
php artisan make:seeder AccountsTableSeeder

Next, we need to input some random values. So in UserTableSeeder.php
, type the following code.

insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
          DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
           DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
            DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
             DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

Okay, for the AccountsTableSeeder.php
file, type the following command.

insert([
		    'user_id' => 1,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 2,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 3,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 4,
		    'account_number' => rand(100000000,999999999)
        ]);
        DB::table('accounts')->insert([
		    'user_id' => 5,
		    'account_number' => rand(100000000,999999999)
        ]);
    }
}

Now, add the following code in the DatabaseSeeder.php
file.

/**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
        $this->call(AccountsTableSeeder::class);
    }

Type the following cmd in your terminal.

php artisan db:seed

Tables are filled with the values.



Step 3: Define one to one relationship.


Make one model called Account.php
by typing this command.

php artisan make:model Account

Now, In User.php
file, write the following function to define the relationship with the Account model.

public function account()
{
   return $this->hasOne('AppAccount');
}

If we want to interact with the database, then we need to Laravel provides one command line interface called tinker.
To boot up the tinker hit the following command.

php artisan tinker

Now, type the following in the tinker.

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

It will display the account details concerning user 1
. So one to one relationship. One user has only one single account. Eloquent determines a foreign key of a relationship based on a model name. In this case, the Account model is automatically assumed to have the user_id foreign key. If you wish to override this convention, you can pass the second argument to the hasOne method.

return $this->hasOne('AppAccount', 'foreign_key');



An Inverse Of The Relationship.


So, we can access an Account
model from the User
. Now, let’s define a relationship on an Account
model that will allow us to obtain a User
that owns an account. We can determine the inverse of the hasOne relationship
using the belongsTo
method.

belongsTo('AppUser');
    }
}

In the example above, Eloquent will try to match a user_id from an Account model to an id on the User model. An Eloquent ORM determines a default foreign key name by examining the name of a relationship method and suffixing the method name with _id. However, if a foreign key on the Account model is not a user_id, you may pass the custom key name as the second argument to a belongsTo
method.

Finally, our tutorial on Laravel One To One Eloquent Relationships
is over.

稿源:AppDividend (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » Laravel One To One Eloquent Relationships

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录