2017-12-21 32 views
0

私はLaravel 5.4を使用しています。私は2台のテーブルdestinationuserとピボットテーブルdestination_userを持っています。ピボットテーブルデータを使用してリレーションテーブルの情報を取得

先テーブル

---|------ 
id | name 
---|------ 
1 | sth 

ユーザテーブル

---|------ 
id | name 
---|------ 
1 | sth 

、最後にピボットテーブル

--------------|-------- 
destination_id| user_id 
--------------|-------- 
1    | 1 
2    | 1 
3    | 2 

私はdestinationUserという名前のピボットテーブルのためのモデルを作成しました。

destinationモデルは次のようになります。

<?php 

namespace App\models; 

use App\Models\User; 
use App\Models\DestinationUser; 
use App\Models\DestinationImage; 
use Illuminate\Database\Eloquent\Model; 

class Destination extends Model 
{ 
    protected $table = 'destinations'; 

    public function user() { 
     return $this->belongsToMany('App\Models\User'); 
    } 

    public function destinationUser() { 
     return $this->hasMany('App\Models\DestinationUser'); 
    } 
} 

私は、ピボットテーブルを使用して、それぞれのユーザーのディテールを持つすべての宛先を取得したいです。

$destinations = $this->destination->with('user', 'destinationUser') 
         ->whereHas('destinationUser', function($query) { 
          $query->where('user_id', user()->id);}) 
         ->paginate(20); 

dd($destinations[0]->destinationUser);は私にdestination iduser idを与えるが、私は、ユーザーの詳細をしたい:私はこれで、これまで試してみました。どうすればこれを実現できますか?私は、クエリの実行速度を探していたとして、テーブルの間違った設計があった

class Destination extends Model 
{ 
    protected $table = 'destinations'; 


    public function destinationUser() { 
     return $this->belongsToMany('App\User'); 
    } 
} 

コントローラ

$destinations = $this->destination->with('destinationUser', function($query) { 
          $query->where('user.id', user()->id);}) 
         ->paginate(20); 
+0

多くの関係が必要ですhttps://laravel.com/docs/5.5/eloquent-relationships#many-to-many – madalinivascu

+0

@madalinivascuより具体的にお聞かせください – vijayrana

+0

ピボットテーブルのテーブル名は何ですか? – madalinivascu

答えて

0

いただきありがとうございます。ピボットのない2つのテーブルではなく、ピボットのある3つのテーブルの負荷と実行時間が増えます。だから、私はそれを理解して修正しました。

+0

'destinationUser()'はピボットテーブルのリレーションです。これを使用して 'destination'テーブルと' user'テーブルの関係を定義しました: 'public function user(){ return $ this-> belongsToMany( 'App \モデル\ユーザー '); } ' – vijayrana

+0

あなたはそれを好きなように名前をつけることができます – madalinivascu

+0

私が必要とするものは多かれ少なかれ多くありましたが、私は1対多の関係を定義しました。それを得た – vijayrana

0

:あなたは、多くの関係に多くを必要とするあなたの助け

関連する問題