'Laravel search in two tables other than using morph
I have three tables, "sales," "person," and "company," where the table "sales" has a morph relationship with the other two. I need to look up the "person" and "company" tables together. If I had another table "customer" with the related morph between "person" and "company," I would vary it this way.
$customers = (new Customer)->whereHasMorph('customer',
[
Person::class,
Company::class,
], function (Builder $query, $type) use ($request) {
if ($request->get('search') !== null) {
if ($type === Person::class) {
$query->whereHas('customer',
function (Builder $query) use ($request) {
$query->whereFulltext(
['document', 'name'],
$request->get('search').':*',
['language' => 'portuguese']
);
});
if ($type === Company::class) {
$query->whereHas('customer',
function (Builder $query) use ($request) {
$query->whereFulltext(
['document', 'company'],
$request->get('search').':*',
['language' => 'portuguese']
);
});
}
}
}
return response()->json($customers->paginate(10));
}
);
The "person" and "company" tables have different fields. I need to solve this problem of the "customer" table.
Solution 1:[1]
$customer = Sales::query()
->with('customer')
->whereHasMorph('customer', function($query) {
$query->where('morphable_type', Person::class)
->orWhere(''morphable', Company::class);
})->get()
then you get the Customer from every sales or $customer = Customer::whereHasMorphable('sales')->get()
the thing is you are trying now to a customer relation on a customer model, so basically you are looking for customers of the customer.
If you are using a customer table...
maybe something like this? ->whereIn('morphable_type', [Person::class, Customer::class])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |