over 4 years ago

sql重新包裝利用

> N+1 query example

We have book and page models, if we want to retreive book from page
The last thing we need is book
Book
From page table
Book.from('pages AS p')
Filtering
Book.from('pages AS p').where('p.id = 200')
Use joins (like array join)
Book.from('pages AS p').where('p.id = 200').joins('INNER JOIN books AS b ON p.book_id = b.id')
Select (the result you want)
Book.from('pages AS p').where('p.id = 200').joins('INNER JOIN books AS b ON p.book_id = b.id').select('b.*, p.name').limit(1)

In rails console

book1 = Book.from('pages AS p').where('p.id = 200').joins('INNER JOIN books AS b ON p.book_id = b.id').select('b.*, p.name').limit(1)
book2 = Book.last
book1.name # has value
book2.name # error
← find_by_xxx Railsfun Git 教學 →
 
comments powered by Disqus