I would look at using eloquent for that, and eloquent has all of the query Builder methods.
How to Get All Orders of Customers Assigned to a Specific Agent Using Query Builder
Hey guys, I've been pulling my hair strings for days trying to write this query but just not getting anywhere. I have these tables:
Agents (Users)
id
name
email
password
created_at
updated_at
Customers
id
agent_id
firstname
lastname
email
created_at
updated_at
Orders
id
customer_id
product_id
amount
Customer_Tags
id
customer_id
name
Products
id
name
I need to write a SQL statement that get all Orders of Customers who are assigned to the current logged in user (by agent_id) and has this tag (ID: 234) but not any of these tags [3343, 445, 333] and has purchased any of these product (IDs: 18, 33, 29).
Just so you understand what tags do. Customers are tagged based on the actions they takes. This is done for marketing purposes. If a customer purchase a product, that customer gets a specific tag attached to them. If they go on to do take another actions like watching the webinar, there's another tag attached and on and on.
This is what I have written.
return DB::table('orders')
->join('customers', 'orders.custom_id', '=', 'customers.id')
->join('customer_tags', function ($join) {
$join->on('customers.id', '=', 'customer_tags.custom_id')
->whereIn('customer_tags.id', [234])
->whereNotIn('customer_tags.id', [3343, 445, 333]);
})
->join('products', 'products.id', '=', 'orders.product_id')
->whereIn('orders.product_id', [18, 33, 29])
->where('customers.agent_id', Auth::user()->id)
->select('orders.invoice_at', 'customers.*', 'products.name')
->get();
Unfortunately, when I customer has 234 and also has any of these tags (3343, 445, 333), it's pulling them into the records. Please help. Thanks
Please or to participate in this conversation.