I want to fetch all invoices a user has raised using the Eloquent ORM.
At the moment, I'm fetching the invoice.id
from a join table UsersInvoices by the user.id
and then looping through and fetching the invoices from the Invoices table based on the id.
$user = Sentry::getUser();
$invoiceIDs = UsersInvoice::where('user_id', '=', $user->id)->get()->toArray();
$invoices = array();
foreach ($invoiceIDs as $key => $row) {
array_push($invoices, Invoice::find($row['invoice_id']));
}
$this->data['title'] = 'Invoices';
$this->data['invoices'] = $invoices;
/** render the template */
App::render('@invoices/pending/index.twig', $this->data);
But I think this could/should be handled by the ORM by modelling the relationship between user and invoices.
It looks as though I should be able to manage this like so by simply posting the user.id
into the invoices table as a foreign key - Maybe I don't need a join table as there is nothing that is unique to the relationship that needs to be stored... ?
Note: Posting from my phone. Sorry, I can't put code examples that way.
If I understand correctly, the relationships between Users and Invoices are
- User hasMany Invoice
- Invoice belongsTo User
If so then you'll need to set it up in the Eloquent models by defining the relationship and methods to get at the relayed data (at least in the User model). The Eloquent ORM expects there to be a user_id field in the invoices table.
Then you can do:
$user = User::find($id);
$user->invoices(); //assuming you put an invoices method in the User model
Or:
$invoice = Invoice::find($id);
$invoice->user(); //assuming you setup a user method in the Invoice model
More info on relationships here: http://laravel.com/docs/eloquent#relationships
It seems that you have stored the user_id
and invoice_id
in a separate table. Simply keep user_id
in the Invoices
table and then use a single query to fetch all. And also do not convert the results to array.
foreach( $invoices as $inv ) {
echo $inv->invoice_id;
}