laravel的with渴望加载

Lazy loading(传统的加载慵懒加载) 和 Eager loading(渴望加载)

渴望加载是减轻N+1的查询问题(Eager loading alleviates the N + 1 query problem.)

举例说明:书本(book)和作者(author)的关系

模型关系:



namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

传统慵懒加载:

$books = App\Book::all();

foreach ($books as $book) {
    echo $book->author->name;
}

慵懒加载方式是先查询出所有书本,再循环查询书本作者姓名
如果有26本书则会进行26次作者的查询,会使用26次的sql语句

渴望模式:

$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}

用with的方式底层(渴望加载)只用了2个sql:
select * from books(获得作者id)
select * from authors where id in (1,2,3,4,5,6…)
这样的节约了数据库的交互

你可能感兴趣的:(php)