2

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();

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I know how to retrieve data with query builder, I want it to be a eloquent Relation so I can use it in other Models
I like to create a custom relationship in my model, but I don't know how to implement it
@Hadu you can use this code as a local scope, but you can't define a relationship like hasMnyThrough or similar, for this case.
Isn't there any way to define custom Relations in laravel
using it as a scope was a great idea! +1 for that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.