2014-01-14 55 views
2

我不知道如何提出問題,所以問題不像描述那樣清楚。但是在這裏。 我想通過查詢子模型來查詢父模型。這裏是基本款:Laravel 4,Retrive變形父模型,查詢子

//Gig.php 
    class Gig extends Eloquent 
{ 
    public function gigable() 
    { 
     return $this->morphTo('profile'); 
    } 
} 

//Band.php 

class Band extends Eloquent { 
public function gigs() 
    { 
     return $this->morphMany('Gig','profile'); 
    } 
} 
//Musician.php 

class Musician extends Eloquent { 
public function gigs() 
    { 
     return $this->morphMany('Gig','profile'); 
    } 
} 

現在,我知道我可以做這樣的事情:

Gig::find(1)->gigable 

有沒有辦法,我可以在一個查詢 和例如用於我的API獲取gigables方式我可以一次返回所有的遊戲。 類似於:

Gig::where('id','>',1)->gigable 

我知道那是行不通的。 如在此我可以這樣做相反,

Band::with('gigs')->where('created_at','<',Carbon::now())->get(); 
+0

你確定你的關係嗎?從[docs](http://laravel.com/docs/eloquent#polymorphic-relations)中,您很困惑PROFILE和GIGABLE – clod986

回答

0

使用方法如下

//Gig.php 
class Gig extends Eloquent { 
    public function gigable() 
    { 
     return $this->morphTo(); 
    } 
} 

//Band.php 
class Band extends Eloquent { 
public function gigs() 
    { 
     return $this->morphMany('Gig','gigable'); 
    } 
} 

//Musician.php 
class Musician extends Eloquent { 
public function gigs() 
    { 
     return $this->morphMany('Gig','gigable'); 
    } 
} 

然後,你就可以拿到演唱會這樣說:

$band = Band::with('gigs')->where('created_at','<',Carbon::now())->get(); 
$gigs = $band->gigs; 

如果這是你想要的......你的問題不清楚

+0

當然,表格應該被正確構造... – clod986