2015-02-06 2 views
0

와 쿼리 나는 다음과 같은 DB 스키마가 있습니다Laravel 관계 : 여러 외부 키

//Pages schema 
    Schema::create('pages', function($table) 
     { 

      $table->increments('id'); 
      $table->softDeletes(); 
      $table->timestamps(); 
      $table->integer('parent_id'); 
      $table->integer('ordination'); 
      $table->unsignedInteger('title_id'); //Refer to strings 
      $table->unsignedInteger('description_id'); //Refer to strings 
      $table->unsignedInteger('url_id'); //Refer to strings 



      //Foreign key 
      $table->foreign('title_id')->references('id')->on('strings'); 
      $table->foreign('description_id')->references('id')->on('strings'); 
      $table->foreign('url_id')->references('id')->on('strings'); 

     }); 



    //Strings 
    Schema::create('strings', function($table) 
      { 

       $table->increments('id'); 
       $table->softDeletes(); 
       $table->timestamps(); 
       $table->text('en'); 
       $table->text('de'); 

      }); 

내가 상대 URL 문자열에서 페이지 개체를 검색 할 수 있습니다 어떻게? 이 웅변 모델

$page= Pages::whereHas('url', function($url) 
    { 
     $url->where('en', '=', 'About'); 

    })->first(); 

: 나는 다음과 웅변 쿼리를 실행 관련 URL에서 페이지 개체를 검색 할 수 있습니다

$page['url']['en'] = 'about' 
$page['title']['en']= 'About title' 
$page['description']['en']= 'About description' 
etc.. 

:

나는 다음과 같은 페이지 객체 또는 배열을 가질 것 :

class Pages extends Eloquent { 

    protected $table = 'pages'; 

    public function url() 

     { 

      return $this->belongsTo('Strings'); 

     } 
} 

이렇게하면 제목, 설명에 대한 문자열 값을 검색하지 않습니다. d가 있지만, 이드 만.

어떻게 할 수 있습니까?

답변

0

관계가 정확합니다. 당신이해야 할 일은 관계를 실제로로드하는 것뿐입니다. 가장 좋은 방법은 열망하는로드입니다. 그것은 최소한으로 DB 쿼리를 줄일 : 열망 부하에

$pages = Page::with('url')->get(); 

$page = Page::with('url')->find(1); 

$page = Pages::with('url')->whereHas('url', function($url){ 
    $url->where('en', '=', 'About'); 
})->first(); 

모든 문자열 관계는 단순히 with() 호출에 추가 : 당신의 대답에 대한

$pages = Page::with('url', 'title', 'description')->get(); 
+0

감사합니다,이 솔루션은 잘 작동! – Spetty