Laravel eloquent - One to many relationships

后端 未结 2 1208
别那么骄傲
别那么骄傲 2021-02-04 21:50

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 relat

相关标签:
2条回答
  • 2021-02-04 22:32

    Laravel 4 has a slightly different syntax , it uses camelCase to build expressions (while L3 uses snake_Case syntax).Laravel's (L4) new syntax is now PSR-1 compliant .

    L3 : $this->belongs_to('Category');
    L4 : $this->belongsTo('Category');
    

    To prove that "eager loading" boosts the performance of your application (by minimizing database queries) , use Laravel's event eco-system .

    // app/routes.php 
    Event::listen('illuminate.query', function($sql) { echo '<h4>' . $sql . '</h4>' ;});
    

    .

    0 讨论(0)
  • 2021-02-04 22:39

    I hope you will find these tips useful.

    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;
    }
    

    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;
    }
    

    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.

    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;
    }
    

    I hope that helps!

    0 讨论(0)
提交回复
热议问题