2014-03-27 65 views
1

我希望能夠編寫一個雄辯的查詢,我可以將此查詢傳遞給此模型函數,以僅返回包含發佈在$ publishDate上的故事的類別。在Laravel中查詢模型

E.G. - 這是我的願望,但我得到以下錯誤「調用未定義的方法照亮\數據庫\查詢\生成器::故事()」

在我的控制器:

Category::orderBy('id', 'ASC')->stories($publishDate)->get(); 

而且在我的模型:

public function stories($publishDate) 
{  
    return $this->hasMany('Workbench\Dailies\Story', 'category_id') 
    ->orderBy('story_title', 'ASC') 
    ->where('publish_date', $publishDate); 
} 

我相信這是非常簡單的事情,但我無法弄清楚。提前致謝。

+0

你想實現什麼? –

+0

對不起,我編輯了我的問題,使其更清楚。 – cmill02s

+0

什麼是完整的錯誤信息?它應該看起來像這樣:調用未定義的方法Illuminate \ Database \ Query \ Builder :: stories() – seeARMS

回答

2

關係:

public function stories() 
{  
    return $this->hasMany('Workbench\Dailies\Story', 'category_id'); 
} 

然後

// $publishedAt is some date you want 

Category::whereHas('stories', function($query) use ($publishedAt) { 
    $query->where('published_at', '=', $publishedAt)->orderBy('story_title','asc'); 
})->orderBy('id','asc')->get(); 
+1

使用這個例子得到以下錯誤:參數2傳遞給Illuminate \ Database \ Eloquent \ Builder :: whereHas()必須是Closure的一個實例,沒有給出。 – cmill02s

+0

現在試試,我對數組做了一個小錯誤 –

+0

這似乎已經完成了這個伎倆,謝謝! – cmill02s

0

我還沒有找到任何類似的方式來做到這一點。我發現的方式是類似(在你的情況下):

Category::join('stories', 'categories.id', '=', 'stories.category_id')->where('stories.publish_date', '=', $publishDate)->orderBy('id', 'ASC')->get(); 

雖然,我更喜歡使用DB::selectDB::raw選擇fitered唯一的ID,然後用我做Category::whereIn('id', <returned IDs>)->get()(在你的情況下)的ORM。

$sql = 'SELECT c.ID FROM categories c LEFT/INNER JOIN stories s ON (c.id = s.category_id) WHERE s.publish_date = ?'; 
$ids = DB::select(DB::raw($sql), array($publishDate)); 
// you can now iterate with array_walk, foreach, for, etc. the args to extract IDs from object rows 
for($i = 0; $i < count($ids); $i++) 
    $ids[$i] = (int) $ids[$i]->id; 

$cats = Category::whereIn('id', $ids)->orderBy('id', 'ASC')->get(); 

不好的是,該部分沒有很好的記錄。我很驚訝,因爲其他的ORM允許這樣的關係查詢。