Laravel eloquent "with" and "where" with multiple tables - php

I've 3 tables on my project:
Mall
Shop
Product
I've a page to search for products in the whole database. I need an option where they can search the product by the mall name. So I built my code like this:
$query = Product::with('shop', 'shop.mall');
if (!empty($data["keyword"])) {
$query = $query->where(function($q) use($data) {
$q->where('shop.mall.name', 'LIKE', '%' . $data["keyword"] . '%')->orWhere('shop.mall.keyword', 'LIKE', '%' . $data["keyword"] . '%');
});
}
But it is showing this error:
Column not found: 1054 Unknown column 'shop.mall.name' in 'where clause'
Is there any problem with my query? Thank you

To search within relation use whereHas(), it creates subquery and returns data filtered in shop.mall.
$query = Product::with('shop', 'shop.mall');
if (!empty($data["keyword"])) {
$query = $query->whereHas('shop.mall',function($q) uses ($data){
$q->where('name', 'LIKE', '%' . $data["keyword"] . '%')->
orWhere('keyword', 'LIKE', '%' . $data["keyword"] . '%');
});
}

Related

Multiple search clause for many-to-many relationships in Laravel

Good day. I have this stuff that has been a little bit problematic for me in my application. I have a Staff model which has a many to many relationship with a Company model. Hence, I have a company_staff table.So, the companies have a unique identifier which is the company code.
The Staff model has information such as first name, lastname, and email etc. Now, I want to perform a search operation using either the firstname, lastname or email, but fetching data for only the company with the unique code (i.e search only within that company). This is the query I came up with below:
$users = Staff::where('first_name', 'like', '%' . $request->search_term . '%')
->orWhere('last_name', 'like', '%' . $request->search_term . '%')
->orWhere('email', 'like', '%' . $request->search_term . '%')
->whereHas('coporate', function ($q) use ($company_code) {
$q->where('company_code', $company_code);
})->get();
I get results but this only returns all the result that match from my "staff" table, behaving as if the "company_code" part of the query does not exist at all. However, if I leave the query as :
$users = Staff::where('first_name', 'like', '%' . $request->search_term . '%')
->whereHas('coporate', function ($q) use ($company_code) {
$q->where('company_code', $company_code);
})->get();
I get the desired result. But, I want to be able to search with both last_name and email as well. Please, how do I go about this?
Try with this code
$users = Staff::where(function ($query) use($request) {
$query->where('first_name', 'like', '%' . $request->search_term . '%')
->orWhere('last_name', 'like', '%' . $request->search_term . '%')
->orWhere('email', 'like', '%' . $request->search_term . '%');
})->whereHas('coporate', function ($q) use ($company_code) {
$q->where('company_code', $company_code);
})->get();
For more : https://laravel.com/docs/6.x/queries#parameter-grouping

How to apply search on deep relation in Laravel?

I want to apply search on the item members which is associated with the item.
I've members relation on my Item model like this
public function members()
{
return $this->hasManyDeep(
'App\Models\Users\TeamMember',
['App\Models\Users\Team'],
[['teamable_type', 'teamable_id'], 'team_id'],
['id', 'id']
);
}
I've done this code for apply search on items on the bases of item's members
$items = Item::query();
->where('title', 'Like', '%' . $keyword . '%')
->with('members')
->orWhereHas('members', function ($query) use($keyword) {
$query->from('users')->where('name', 'Like', '%' . $keyword . '%');
})->get();
this relation will be return an array of members. Now It's giving me error called -
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'team_members.team_id' in 'on clause' (SQL: select * from `items` and `title` Like %test% or exists

how to convert this query in eloquent?

I am a beginner laravel developer who wants to convert this query into an eloquent ORM. I know eloquent make it small. I search a lot but was always stuck in where condition It working perfectly but need to change in eloquent.
Product::join('subcategories', 'subcategories.id', '=',
'products.subcategory_id')
->join('categories', 'categories.id', '=', 'products.category_id')
->WHERE('products.name', 'like', '%' . $search . '%')
->orWHERE('subcategories.name', 'like', '%' . $search . '%')
->orWHERE('categories.name', 'like', '%' . $search . '%')
->orWHERE('products.description', 'like', '%' . $search . '%')
->orWHERE('products.price','=', $search)
->select('products.*')
->paginate(5);
In the second query, I want to select User where the role is admin but id not equal to 1.
User::where(['role'=>admin, 'id',!=,1])->first();
I am using this please guide me
User::where('role',admin)->where('id',!=,1)->first();

Can anyone help me to solve an ambiguous error when search?

$students = Student::select('students.*', 'users.email')->join('users', 'students.user_id', 'users.id')->orderBy("id", "desc")->skip($page * $pageSize)->take($pageSize);
if (request('se') != "" || request('se') != null) {
$se = request('se');
$se = str_replace("+", " ", $se);
$students = $students
->where(function ($q) use ($se) {
$q->where('students.student_number', 'like', '%' .$se. '%')
->orWhere(DB::raw("CONCAT(`first_name`, ' ', `last_name`)"), 'LIKE', '%' . $se . '%')
->orWhere('students.gender', $se)
->orWhere('students.phone', 'like', '%' .$se. '%')
->orWhere('email', 'like', '%' .$se. '%');
});
}
$students = $students->orderBy('id', 'DESC')->get();
when I search in the list I got Integrity constraint violation: 1052 Column 'first_name' in where clause is ambiguous error.
This got when join the table because both students and users table have first name and last name columns, but I have retrieved from only students table, I didn't understand why this appears again!
Are there any better solution for this?
Change the first_name and last_name to students.first_name and students.last_name respectively

Laravel Search Reference Second Model/Collection/Table with orWhereHas?

I'm trying to implement search functionality within my blade for my Script model. It performs fine for everything related to searching directly within the Script collection/table. However, my users also will need to be able to enter in a Patient first_name or last_name and search for the script records within the Script table that belong to the Patient being searched for. These are connected with a hasMany/belongsTo relationship. I'm trying to reference data from the Patient table in the Script results.
I've tried (with help from SO already) to implement orWhereHas and reference the patients table, but something with my syntax must be off.
The error messages I'm getting from trying to reference 'patients' with orWhereHas returns:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'scripts.patients_id' in 'where clause' (SQL: select count(*) as aggregate from `scripts` where exists (select * from `patients` where `scripts`.`patients_id` = `patients`.`id` and (`first_name` like %% or `last_name` like %%)))
This probably would work if it referenced patient_id, which is the column name for the patients foreign key. I don't know if there is a way to do that?
When I change 'patients' to 'patient', I receive the error:
Call to undefined method App\Script::patient()
Models
Patient hasMany Script
Script belongsTo Patient (patient_id)
Script Blade
{{ Form::text('search', $search, ['class' => 'form-control form-control-sm', 'placeholder' => 'Search Scripts...']) }}
{{Form::submit('Search', ['class' => 'btn btn-primary btn-sm'])}}
ScriptController
$search = $request->search;
$patients = Patient::all();
$scripts = Script::
when($search, function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query
->where('prescribe_date', 'LIKE', '%' . $search . '%')
->orWhere('status', 'LIKE', '%' . $search . '%')
->orWhere('efax_reference', 'LIKE', '%' . $search . '%')
->orWhere('efax_confirmation', 'LIKE', '%' . $search . '%');
});
})
->orWhereHas('patients', function ($query) use ($search) {
$query->where('first_name', 'like', '%' . $search . '%')
->orWhere('last_name', 'like', '%' . $search . '%');
})
->paginate(25);
I expect that if someone searches for a patient name within the search input on the Scripts table/model, they are able to cross-reference the Patients table/model and display the Scripts records that are foreign_key'ed to those Patients.
EDIT:
Patient model
// One Patient has Many Scripts relationship
public function scripts() {
return $this->hasMany('App\Script');
}
Script model
// Many Scripts to One Patient relationship
public function patients() {
return $this->belongsTo('App\Patient');
}

Categories