I have two models:
Order
Customer
I have customer_id
in orders
table. Customer details (name, phone, email etc) in customers
table. But I am writing query for orders table.
Now, I want to search with Customer Name on Orders but in Orders table I just have customer_id
.
How will I link up with customers table so that I can search with Customer Name. I want to do that with Eloquent.
How is this possible?
My Answer:
You can achieve this by defining a relationship between the Order and Customer models in Laravel using Eloquent.
In your Order model, you can define a belongsTo relationship to the Customer model like this:
php
class Order extends Model
{
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id');
}
}
Then, you can use this relationship to search for orders based on the customer's name like this:
php
$orders = Order::whereHas('customer', function ($query) use ($customerName) {
$query->where('name', 'like', '%' . $customerName . '%');
})->get();
This will retrieve all orders where the customer's name matches the provided search term.
Make sure to replace 'name' with the actual column name in the customers table where the customer's name is stored.
Rate this post
3 of 5 based on 9504 votesComments