dongwu9647 2014-09-13 22:53
浏览 81
已采纳

在Eloquent ORM中按用户ID获取发票

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... ?

  • 写回答

2条回答 默认 最新

  • dongyishe6689 2014-09-14 19:19
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog