2017-12-21 44 views
0

Laravel 5.4를 사용하고 있습니다. 나는 2 개의 테이블 destinationuser과 피벗 테이블 destination_user을 가지고있다.피봇 테이블 데이터를 사용하여 관계 테이블 정보 가져 오기

대상 테이블

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

사용자 테이블

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

내가 destinationUser라는 이름의 피벗 테이블에 대한 모델을 만들어

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

마지막으로 피벗 테이블.

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을 제공하지만 사용자 세부 사항을 원한다. 이것을 어떻게 할 수 있습니까? 당신의 도움이

+0

많은 관계가 필요합니다. https://laravel.com/docs/5.5/eloquent-relationships#many-to-many – madalinivascu

+0

@madalinivascu – vijayrana

+0

피봇 테이블의 테이블 이름은 무엇입니까? – madalinivascu

답변

0

주셔서 감사합니다 당신은 많은 관계로 많은 필요합니다

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

'destinationUser()'는 피봇 테이블에 대한 관계입니다. 다음과 같이'user' 테이블과'destination' 테이블의 관계를 정의했습니다 :'public function user() { return $ this-> belongsToMany ('App \ 모델 \ 사용자 '); }' – vijayrana

+0

당신은 원하는 이름으로 부를 수 있습니다. – madalinivascu

+0

내가 원하는 것은 많은 것이었지만, 나는 많은 관계를 정의했습니다. 알았어 – vijayrana

0

내가 쿼리의 빠른 실행을 위해 검색되면서, 테이블의 잘못된 디자인이 있었다. 피벗이없는 2 개의 테이블이 아닌 3 개의 테이블에 대해 더 많은로드 및 실행 시간이 있습니다. 그래서, 나는 그것을 알아 내고 고쳤다.