Knex.js One to Many table join
The scenario:
quotes tables:
first_name, email, estimate, etc.
quote_notes:
id, note, quote_id
So, quotes has_many quote_notes. I am trying to join that when doing my query in my quote model.
function getAllNotes() {
return db('quote_notes')
.select('quote_notes.id', 'note', 'quote_notes.created_at', 'quote_id')
.join('quotes', 'quote_notes.quote_id', 'quotes.id')
.orderBy('id')
}
Whenever I do the get request to the path, it returns all quote_notes for any quote I look at.
router.get('/:id/notes', (req, res) => {
const {id} = req.params;
Quotes.getAllNotes(id).then((users) => {
res.status(200).json(users);
});
});
This is my request for reference:
const getQuoteNotes = async () => {
let quoteNotes = await axiosWithAuth().get('/quotes/' + quoteId + '/notes');
setQuoteNotes(quoteNotes.data);
}
And my table for quote_notes:
table.bigInteger('quote_id')
.unsigned()
.index()
.references('id')
.inTable('quotes')
Join should be used before select
return db('quote_notes')
.join('quotes', 'quotes.id','=', 'quote_notes.quote_id')
.select('quote_notes.id', 'note', 'quote_notes.created_at', 'quote_id')
.orderBy('id')
Your last edit changes things, if you just want the notes of certain quote you should query for the notes by quote_id
db('quote_notes')
.where('quote_id', quoteId )
.orderBy('id')