我刚刚开始使用 laravel v3,并试图通过创建博客来解决 Eloquent 一对多关系,我的帖子与类别有多对一的关系(每个帖子都链接到一个类别)。
我有以下表格,其中包含以下字段:
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 来获取所有帖子:
category::find(2)->posts()->get())
我只需要帮助找出如何获取所有帖子,并获取它们相应的类别。所以在一天结束时,我可以在 View 中输出如下内容:
{$post->title} - Category: {$post->category->name}
感谢您的帮助!
最佳答案
我希望这些提示对您有用。
在 post 模型上,将 categories
函数重命名为 category
。 belongs_to
关系是单数的,因此这篇文章只有一个类别。
关系也有简写形式,这种简写语法很有用,因为它使用起来更简洁并且结果被缓存。这是一个例子:
$category = Category::find(1);
foreach($category->posts as post) {
echo $post->title;
}
现在是如何获取所有帖子及其相关类别的示例:
$posts = Post::all();
foreach($posts as $post) {
echo $post->category->name;
}
现在,在执行第二个示例时,您会很快注意到一件事,即您拥有的每个帖子的查询数量都会增加。这称为 N+1 效应。例如,如果您有 5 个帖子,将执行一个查询以获取这些帖子。然后在循环中我们正在执行查询以获取类别。这导致总共 6 个查询。
要解决这个问题,请使用预先加载,这会将我们示例中的 6 个查询减少到 2 个。
$posts = Post::with('category')->all();
foreach($posts as $post) {
echo $post->category->name;
}
希望对您有所帮助!
关于php - Laravel Eloquent - 一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12941397/