[英]Querying Models in Laravel
我希望能夠編寫一個雄辯的查詢,將該查詢傳遞給此模型函數,以僅返回在$ publishDate上發布了故事的類別。
EG-這是我想要的,但出現以下錯誤“調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: stories()”
在我的控制器中:
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);
}
我相信這很簡單,但是我不太清楚。 提前致謝。
關系:
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();
我還沒有找到以任何類似方式執行此操作的方法。 我發現的方式類似於(在您的上下文中):
Category::join('stories', 'categories.id', '=', 'stories.category_id')->where('stories.publish_date', '=', $publishDate)->orderBy('id', 'ASC')->get();
雖然,我更喜歡使用DB::select
和DB::raw
來選擇合適的ID,然后才使用ORM選擇Category::whereIn('id', <returned IDs>)->get()
(在您的上下文中) 。
$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允許這種關系查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.