Laravel雄辩 - 一对多的关系 [英] Laravel eloquent - One to many relationships
问题描述
我刚刚开始使用laravel v3,并试图围绕雄辩的一对多关系围绕创建一个博客,我有一个与类别有多个关系的帖子(每个帖子都链接到一个类别)。
I have just got started with laravel v3 and am trying to wrap my head around eloquent's One-To-Many relationships by creating a blog, I have posts that have a many to one relationship with categories (Each Post is linked to a category).
我有以下表格,包含以下字段:
I have the following tables with the following fields:
帖子:id,title,body,date_created,category_id
posts: id, title, body, date_created, category_id
类别:id,name
我有以下两种模式:
class Category extends Eloquent
{
public function posts()
{
return $this->has_many('Post');
}
}
class Post extends Eloquent
{
public function categories()
{
return $this->belongs_to('Category');
}
}
我想出了如何通过传递所有的帖子类别ID:
I figured out how to get all posts by passing in a category id:
category::find(2)->posts()->get())
我只需要帮助,了解如何获取所有帖子,并获得相应的类别。所以在一天结束的时候,我可以输出这样的东西:
I just need help on finding out how to get all posts, and get their corrisponding categories. So at the end of the day in the view I can output something like this:
{$post->title} - Category: {$post->category->name}
感谢任何帮助! p>
Thanks for any help!
推荐答案
我希望你会发现这些提示很有用。
I hope you will find these tips useful.
模型将类别
功能重命名为类别
。一个 belongs_to
关系是单数,所以这篇文章有一个,只有一个类别。
On the post model rename the categories
function to category
. A belongs_to
relation is singular, so this post has one and only one category.
关系也有一个短暂的,这种速记语法是有用的,因为它使用起来比较干净,结果被缓存。举个例子:
Relations also have a short hand, this shorthand syntax is useful because it is cleaner to use and the results are cached. Heres an example:
$category = Category::find(1);
foreach($category->posts as post) {
echo $post->title;
}
现在一个如何获取所有与他们相关类别的帖子的例子: / p>
Now an example of how to get all the posts with their related categories:
$posts = Post::all();
foreach($posts as $post) {
echo $post->category->name;
}
现在有一件事你会很快注意到,第二个例子是每个帖子的查询都会增加。这被称为N + 1效应。例如,如果您有5个帖子,则将执行一个查询以获取这些帖子。然后在循环中,我们正在执行一个查询来获取类别。这样可以得到6个查询。
Now one thing you will quickly notice when doing this second example is the number of queries increase for each post you have. This is called the N+1 effect. Example, if you have 5 posts, one query will be executed to get those posts. Then in the loop we are executing a query to get the category. This results in 6 total queries.
为了解决这个问题,使用eager加载,将我们的例子中的6个查询减少到2。
To solve this problem, use eager loading, which reduces those 6 queries in our example down to 2.
$posts = Post::with('category')->all();
foreach($posts as $post) {
echo $post->category->name;
}
我希望有帮助!
这篇关于Laravel雄辩 - 一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!