san*_*anu 6 php many-to-many eager-loading laravel
我被困在这里从2-3小时开始尝试.
我有很多关系:
class Category extends Model
{
public function news()
{
return $this->belongsToMany('App\News');
}
}
class News extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试获取相关类别的最新5条新闻:
$front_categories = Category::with(array(
'news'=>function($query){
$query->where('publish','1')->orderBy('created_at', 'desc')->take(5);}))
->where('in_front', 1)->get();
Run Code Online (Sandbox Code Playgroud)
上面的查询对我不起作用,它总共给出了五个结果,而不是每个类别的5个结果.
根据我对 Laravel 的了解,你可以尝试这样做。
\n\nclass Category {\n\n public function recentNews()\n {\n return $this->news()->orderBy('created_by', 'DESC')\n ->take(5);\n }\n}\n\n// Get your categories\n$front_categories = Category::where('in_front', 1)->get();\n\n// load the recent news for each category, this will be lazy loaded\n// inside any loop that it's used in.\nforeach ($front_categories as $category) {\n $category->recentNews;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这与 L\xc3\xaa Tr\xe1\xba\xa7n Ti\xe1\xba\xbfn Trung 的答案具有相同的效果,并导致多个查询。它还取决于您是否重用此功能。如果它是一次性的,最好将其放在其他地方。其他方法也可以更加动态,例如创建一个返回类别集合的方法,您可以要求它提供某个数字:
\n\nclass CategoriesRepository {\n\n public static function getFrontCategories(array $opts = []) {\n\n $categories = Category::where('in_front', 1)->get();\n\n if (!empty($opts) && isset($opts['withNewsCount'])) \n {\n foreach ($categories as $category) \n {\n $category->recentNews = static::getRecentNewsForCategory(\n $category->id,\n $opts['withNewsCount']\n );\n }\n }\n\n return $categories;\n }\n}\n\n$front_categories = CategoriesRepository::getFrontCategories([\n 'withNewsCount' => 5\n]);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
519 次 |
| 最近记录: |