0
0

Laravelでneo4jを使ってみる③モデル

Posted at

※modelのフォルダを変更しています。

Userモデルに関連したRaceモデルを作ります。

(User) → (Race)

##1)モデルクラス作成

$ php artisan make:model Models/Race
app/Models/Race.php
<?php

namespace App\Models;
use Vinelab\NeoEloquent\Eloquent\Model as NeoEloquent;

class Race extends NeoEloquent 
{
    //
    protected $label = 'Race'; 
    protected $fillable = ['name']; 
}

##2)HasOne(1対1)

app/Models/User.php
class User extends NeoEloquent implements
{

    public function race()
    {
        return $this->hasOne('app\Models\Race','ENTRY');
    }

return $this->hasOne('モデル','リレーション名');

web.php
    $user = User::first();
    $race = new Race(['name' => 'レース']);
    $relation = $user->race()->save($race);

上記を実行すると下記のようにデータが追加される。

(User) →[:ENTRY] → (Race{name:"大会"})

※hasOneでsaveを複数回行うと、新規nodeが作成され、リレーションは最新のnodoのみになる。
例)大会1、大会2、大会3を連続でsaveすると、Raceノードは3つでリレーションは1つのみ保持される。

(User) (Race{name:"大会1"})
(User) (Race{name:"大会2"})
(User) →[:ENTRY] → (Race{name:"大会3"})

##3)HasMany(1対多)

app/Models/User.php
class User extends NeoEloquent implements
{

    public function races()
    {
        return $this->hasMany('app\Models\Race','ENTRY');
    }
web.php
    $user = User::first();
    $race = new Race(['name' => 'レース']);
    $relation = $user->races()->save($race);

※hasOneと違いリレーションはすべて維持したまま。
例)大会1、大会2、大会3を連続でsaveすると、Raceノードは3つでリレーションも3つ保持される。

(User) →[:ENTRY] → (Race{name:"大会1"})
(User) →[:ENTRY] → (Race{name:"大会2"})
(User) →[:ENTRY] → (Race{name:"大会3"})

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0