Php 在Elount ORM中按用户id获取发票
我想获取用户使用雄辩的ORM提出的所有发票 目前,我正在通过Php 在Elount ORM中按用户id获取发票,php,laravel,orm,eloquent,Php,Laravel,Orm,Eloquent,我想获取用户使用雄辩的ORM提出的所有发票 目前,我正在通过user.id从联接表UsersInvoices获取invoice.id,然后根据id循环并从invoices表获取发票 $user = Sentry::getUser(); $invoiceIDs = UsersInvoice::where('user_id', '=', $user->id)->get()->toArray(); $invoices = array(); foreach ($invoiceIDs
user.id
从联接表UsersInvoices获取invoice.id
,然后根据id循环并从invoices表获取发票
$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);
但我认为这可以/应该由ORM通过建模用户和发票之间的关系来处理
看起来我应该能够通过简单地将
user.id
作为外键发布到invoices表中来管理这一点-也许我不需要联接表,因为需要存储的关系没有唯一的东西 您似乎已将用户id
和发票id
存储在单独的表中。
只需将user\u id
保留在Invoices
表中,然后使用单个查询获取所有。
也不要将结果转换为数组
foreach( $invoices as $inv ) {
echo $inv->invoice_id;
}
注意:从我的手机发帖。对不起,我不能这样写代码示例 如果我理解正确,用户和发票之间的关系是
- User hasMany Invoice
- Invoice belongsTo User
如果是这样,那么您需要在雄辩的模型中通过定义关系和获取中继数据的方法来设置它(至少在用户模型中)。雄辩的ORM希望发票表中有一个用户id字段
然后你可以做:
$user = User::find($id);
$user->invoices(); //assuming you put an invoices method in the User model
或:
有关关系的更多信息,请参见此处:是的,您肯定应该使用不同的方法,而不是对每个发票运行查询。您可以使用关系(可能没有透视表)。您的示例
User::relation()
是错误的-您不能这样做。谢谢,Jarek!我更正了伪代码,使其更加准确。
$invoice = Invoice::find($id);
$invoice->user(); //assuming you setup a user method in the Invoice model