Skip to content
Sumit Patil edited this page Oct 10, 2016 · 3 revisions

One To One relationship

Suppose, we want User model to be associated with one Phone. To define this relationship, we place a phone method on the User model. The phone method should return the results of the hasOne method on the base Eloquent model class.

Step 1 : Migration php artisan orient:make create_users_table --create=users php artisan orient:make create_phones_table --create=phones

Step 2 : Edit migration files which are created database/migrations/ folder

20xx_xx_xx_xxxxxx_create_users_table.php

use Sgpatil\Orientdb\Schema\Blueprint;
use Sgpatil\Orientdb\Migrations\Migration;

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name');
			$table->string('email');
			$table->string('password');
		});
	}

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

}

20xx_xx_xx_xxxxxx_create_phones_table.php

use Sgpatil\Orientdb\Schema\Blueprint;
use Sgpatil\Orientdb\Migrations\Migration;

class CreatePhonesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('phones', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('code');
			$table->string('number');
			$table->timestamps();
		});
	}

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

}

After adding the fields in migration file run

php artisan orient:install

This will create migration table at database then run

php artisan orient:migrate

This will run the migration file and will create 2 tables in database. After this we will modify the models

User.php

<?php
namespace App;
class User extends \Orientdb
{
    protected $fillable = ['name', 'email'];
    
    public function has_phone()
    {
        // both the arguments are classes with there namespace
        // We will create them in following steps
        return $this->hasOne('App\Phone', 'App\Has');
    }
}
?>

Phone.php

<?php
namespace App;

class Phone extends \Orientdb
{
    protected $fillable = ['code', 'number'];
    
}
?>

Has.php

<?php
namespace App;

class Has extends \Orientdb
{
    protected $fillable = ['home', 'office'];
    
}
?>

Creating relationship

$user =   User::create(['name'=>"Sumit", 'email' => "[email protected]"]); // Create User node
$phone = new Phone(['code' => 963, 'number' => '98555533']); // Create Phone node
$relation = $user->has_phone()->save($phone); // Creating relationship

Congratulations!, You have just created a relationship from User to Phone

[User]->[Has]->[Phone]

Clone this wiki locally