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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?