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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度