2016-05-11 43 views
1

ユーザーテーブル:にはzone_idのフィールドがあります。Laravel - 正しい関係を定義する

ゾーンテーブル:にはworld_idフィールドがあります。

  • 各ユーザはZONE_ID = 1

  • 、例えば、1つのゾーンとすることができる各ゾーンは、例えば、一つの世界に属する - world_id = 5

を私の望む出力は、ユーザーゾーンと世界の情報を返しています。

これは私がどんな関係を設定せずにそれを作ることができる方法である。

$zone = Zone::find($user->zone_Id); 
$world = World::find($zone->world_id); 
$data = $user; 
$data['zone'] = $zone; 
$data['zone']['world'] = $world; 

私の質問は..私は関係がクリーンなコードのために使用することができると確信しているが、私は設定するかどうかはわかりませんそれをアップ。

  1. 私は現在のコードに固執するか、関係を定義する必要がありますか?
  2. 1の答えがの場合、関係はと定義されます。これらの3つのモデルの間に正しい関係がありますか?

解決方法1:

`public function getZone(Request $request) 
    { 
     $token = $request->input('token'); 
     $user = JWTAuth::toUser($token); 
     // Simplest example using relationships 
     $userWithZone = User::with('zone.world')->find($user->id); // You'll get the `zone` relationship info here, too 
     return $userWithZone; 
    }` 

エラー:returns "Call to a member function getQuery() on null"

答えて

1

ここでは、あなたが雄弁関係でこれを実現することができる方法の例です。

// User.php 
class User 
{ 
    public function zone() 
    { 
     return $this->belongsTo(Zone::class); 
    } 
} 

// Zone.php 
class Zone 
{ 
    public function world() 
    { 
     return $this->belongsTo(World::class); 
    } 
} 

最も簡単な例として使用して関係

$user = User::with('zone.world')->find($id); // You'll get the `zone` relationship info here, too 
あなたも

$user = User::with(['zone' => function($query) { 
    $query->with('world') 
      ->select('id', 'zone_name', 'world_id'); 
})->select('username', 'zone_id')->find($id); 

かをしたい場合は、あなたの関係でより複雑なを取得することができ

...

$user = User::with(['zone' => function($query) { 
    $query->with(['world' => function($query2) { 
     $query2->select('id', 'world_name'); 
    }])->select('id', 'zone_name', 'world_id'); 
})->select('username', 'zone_id')->find($id); 

あなたの結果$userのようなものになります。私はあなたの最初のソリューションをしようと、エラーを持っている

'user' => [ // This is a Collection 
    'username', 
    'email', 
    'zone_id', 
    'zone' => [ // This is a Collection 
     'id', 
     'zone_name', 
     'world_id', 
     'world' => [ // This is a Collection 
      'id', 
      'world_name' 
     ] 
    ] 
]; 
+0

を、私は情報 – TheUnreal

+0

私の更新を参照してくださいと私の質問を更新しました。私はその関係の中で「リターン」を欠いていました。 – tptcat

+0

私はその質問を理解しているか分からない。最初の質問を更新できますか? – tptcat

関連する問題