简体   繁体   中英

Laravel 5.1 / Eloquent: How do I use a 3rd table to select from the second table

I have three tables: users, purchase_orders and approvals.

One purchase_order has to be approved by multiple users.

When a new purchase_order gets created, I also create 3 pending approvals belonging to that PO.

The approvals table has a field allowed_user_type that determines who can approve it.

I can't figure out, what is the Eloquent way of selecting the pending purchase orders that can be approved by a specific user, as these are determined from the approvals table.


So far I can pull the pending approvals from the approvals table for a user with the following in the User model.

public function approvals_pending()
{
    return $this->hasMany('App\Approval', 'allowed_user_type', 'user_type')
            ->where('approved', '=', 0);
}

The question is, how do I combine this with a theoretical filter?

I mean ideally, I would love to write:

return $this->hasMany('App\PO')->whereIn('id', '=', $this->approvals_pending()->get()->po_id);

Or something like that...

Any ideas would be greatly appreciated.

OK, for anyone interested I found a solution:

It's very close to what I thought I would have to write.

The lists method basically creates a single array out of the selected field, so it can be plugged-in directly to a whereIn method like so:

    return \App\PO::whereIn('id', $this->approvals_pending()->lists('po_id'));

I don't know if this is the most Eloquent way of doing this but it does work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM