Hadi Sharghi
Hadi Sharghi

Reputation: 1005

Laravel hasMany relation with custom query

I have a table for Product Orders. An order belongs to a Customer (Buyer) whose id is in the order record. I can get customer orders with default hasMany relation

// Customer model
public function orders() {
  return $this->hasMany(Order::class);
}

In the other hand, as each Product belongs to a Customer (different from the one whose id is in the order) Customer (Seller), I want the other Customer can see the list of Orders which have his Product in it.

I want to get list of customer Orders when either he is the seller or the buyer. I want to create a custom relation or modify a relation to achieve the result.

Is it possible to achieve this with Laravel's relations?

Customers table:

---------------------------
| customer_id |   name    | 
---------------------------
| 1           | seller    |
| 2           | buyer     |

Products table:

---------------------------------------
| product_id  |   name    | seller_id |
---------------------------------------
| 101         | iPhone 6s |   1       |

Orders Table

----------------------------------------
| order_id  | customer_id | product_id |
----------------------------------------
| 500       | 2           |   101      |

When using simple hasMany relation, buyer will see order 500 in his orders list.

$buyer->orders();

I want to create a single relation that when I call it from seller's side, he can see order 500 in his orders list.

$seller->orders();

Upvotes: 2

Views: 6366

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

I assume you've defined all the relationships. Use where() to filter by a buyer and orWhereHas() to filter by a seller:

Order::where('customer_id', auth()->id())
    orWhereHas('product.seller', function($q) {
        $q->where('id', auth()->id());
    })
    ->get();

If you have other where clauses in the query, wrap where() and orWhereHas() with the where() closure.

Upvotes: 3

Related Questions