Need some help to convert SQL query to Laravel eloquent - laravel

I have this SQL query:
SELECT * FROM books WHERE id IN
(SELECT book_id FROM `author_book` WHERE author_book.author_id IN
(SELECT id FROM authors WHERE self_name like "%ори%" OR father_name LIKE "%ори%" OR family_name LIKE "%ори%"))
It works, but I need convert to Laravel eloquent.
I try this:
DB::select("SELECT * FROM books WHERE id IN "
. "(SELECT book_id FROM `author_book` WHERE author_book.author_id IN "
. "(SELECT id FROM authors WHERE self_name like '%" . $attributes['search'] . "%' "
. "OR father_name LIKE '%" . $attributes['search'] . "%' "
. "OR family_name LIKE '%" . $attributes['search'] . "%'))");
And this works, but can't use pagination. Does anyone have any idea?

If you want Eloquent solution, use the whereHas() method:
Book::whereHas('authors', function($q) use($search) {
$q->where('self_name', 'like', '%' . $search . '%')
->orWhere('father_name', 'like', '%' . $search . '%')
->orWhere('family_name', 'like', '%' . $search . '%')
})->get();
This will work if you properly defined relationships. In the Book model:
public function authors()
{
return $this->belongsToMany(Author::class);
}
And in the Author model:
public function books()
{
return $this->belongsToMany(Book::class);
}

Related

How to get foreign key data in main field Laravel

I have a problem connecting to the data for searching the customer's name because I only identify the id as a foreign key. How can I get data from the customer table? I tried using a join table but no got no result.
public function render()
{
$search = $this->searchTerm;
$data = Order::with('customer')->where('user_id', Auth::id())
->where(function ($query) use ($search) {
$query->where('customer_id', 'like', '%' . $search . '%') // <- this field linked in customers table to get name of customer
->orWhere('orderNumber', 'like', '%' . $search . '%');
})->orderBy('id', $this->sortDirection)->paginate(9);
return view('livewire.dashboard.orders.list-order', compact('data'));
}
If I am right I think you are trying to search for customer name through customer relationship
You can do it like this:
$search = $this->searchTerm;
$data = Order::where('user_id', Auth::id())->with(['customer' =>
function($query) use($search){
$query->where('name','like', '%' . $search . '%')
->orWhere('orderNumber', 'like', '%' . $search . '%');
}])->orderBy('id', $this->sortDirection)->paginate(9);

Adding secondary query to query based on parameter in laravel

I am trying to do a complex query based on the input fields of the form.
public function search(Request $request){
$borrado =
$activo = 0;
$models = array();
$escandallos = Scandal::all();
foreach ($escandallos as $escandallo){
if (in_array($escandallo->modelo, $models)) {
}else{
array_push($models, $escandallo->modelo);
}
}
$query = Model::where('modelo', 'like', '%' . $request['modelo'] . '%')
->where('prototipo', 'like', '%' . $request['prototipo'] . '%')
->where('oficial', 'like', '%' . $request['modofi'] . '%')
->where('usuario_realiza', 'like', '%' . $request['usuario'] . '%')
->where('tipo', 'like', '%' . $request['tipo'] . '%')
->where('activa', 'like', '%' . $activo . '%');
if($request['referencia'] || $request['proveedor']){
/** Here i want to do this DB:raw where in clause if reference or provider is in request and need to search in other table*/
$query->DB::raw("where (id_escandallo,id_version) in (select id_escandallo,id_version from escandallo_p where referencia ='".$request['referencia']. "' and proveedor ='".$request['proveedor']."'");
}
$query->orderBy('modelo','desc');
$query->orderBy('id_version','asc');
$scandals = $query->paginate(100);
dd($scandals);
return view('designdoc.escandallos',['scandals'=> $scandals],['models'=>$models]);
}
This return this error:
Property [DB] does not exist on the Eloquent builder instance.
Thank you in advance, any help would be appreciated.
Best regards.
Use ->whereRaw()
$query->whereRaw(...);
also, you can simplify this part
if($request['referencia'] || $request['proveedor']){
$query->whereRaw(...); // but dont use 'where' in the string, its already prepended
}
to this
$query->when($request['referencia'] || $request['proveedor'], function ($q) use ($request) {
$q->whereRaw(...)
});
it is good so that you can chain it with previous command

Laravel 8 - How to query for a part of a name in a full name across multiple fields?

I have a query in laravel which looks like this:
$adeudos = Adeudo::select('adeudo.*', 'adeudo_estatus.estatus', 'prestacion.nombre AS nombrePrestacion', 'vias_recuperacion.via AS viaRecuperacion', 'ente_publico.rfcPatronal AS rfcEnte',
'ente_publico.nombre AS nombreEnte', 'relacion_laboral.numeroEmpleado', 'derechohabiente.rfc', 'derechohabiente.nombre', 'derechohabiente.primerApellido', 'derechohabiente.segundoApellido')
->join('adeudo_estatus', 'adeudo_estatus.id', 'adeudo.idEstatus')
->join('prestacion', 'prestacion.id', 'adeudo.idPrestacion')
->join('vias_recuperacion', 'vias_recuperacion.id', 'adeudo.idViaRecuperacion')
->join('relacion_laboral', 'relacion_laboral.id', 'adeudo.idRelacionLaboral')
->join('derechohabiente', 'derechohabiente.id', 'adeudo.idDerechohabiente')
->join('ente_publico', 'ente_publico.id', 'relacion_laboral.idEnte')
->when($search, function($query, $search){
/*$query = $query->orWhere('derechohabiente.rfc', 'LIKE', '%{$search}%');*/
$query = $query->orWhereRaw("derechohabiente.rfc like '%$search%'");
$query = $query->orWhereRaw("derechohabiente.numeroIssstezac like '%$search%'");
return $query;
});
I want to search in multiple fields in case one of them matches the $search variable. The problem I'm having is with making a query that can filter if the $search variable contains a part or all of the full name of the 'derechohabiente' object.
The full name is divided in multiple fields, though, there is:
name
middleName
lastName
So, if the full name is John Jeremy Jacobs, I'd like the query to return that name if the $search variable has something like "ohn", "ohn Jeremy", "John Jeremy J", etc.
$adeudos = Adeudo::select('adeudo.*', 'adeudo_estatus.estatus', 'prestacion.nombre AS nombrePrestacion', 'vias_recuperacion.via AS viaRecuperacion', 'ente_publico.rfcPatronal AS rfcEnte', 'ente_publico.nombre AS nombreEnte', 'relacion_laboral.numeroEmpleado', 'derechohabiente.rfc', 'derechohabiente.nombre', 'derechohabiente.primerApellido', 'derechohabiente.segundoApellido')
->join('adeudo_estatus', 'adeudo_estatus.id', 'adeudo.idEstatus')
->join('prestacion', 'prestacion.id', 'adeudo.idPrestacion')
->join('vias_recuperacion', 'vias_recuperacion.id', 'adeudo.idViaRecuperacion')
->join('relacion_laboral', 'relacion_laboral.id', 'adeudo.idRelacionLaboral')
->join('derechohabiente', 'derechohabiente.id', 'adeudo.idDerechohabiente')
->join('ente_publico', 'ente_publico.id', 'relacion_laboral.idEnte')
->when(!empty($search), function($q, $search) {
$q->where(function($query) use ($input) {
$query->orWhere(DB::raw('CONCAT(derechohabiente.first_name, " ", derechohabiente.middle_name," ",derechohabiente.last_name)'), 'LIKE', '%' . $search . '%')
->orWhere(DB::raw("CONCAT('derechohabiente.first_name', ' ', 'derechohabiente.last_name')"), 'like', '%' . $search . '%')
->orWhere(DB::raw("CONCAT('derechohabiente.last_name', ', ', 'derechohabiente.first_name')"), 'like', '%' . $search . '%')
->orWhere(DB::raw("CONCAT('derechohabiente.first_name', ' ', 'derechohabiente.middle_name', ' ', 'last_name')"), 'like', '%' . $search . '%')
->orWhere(DB::raw("CONCAT('derechohabiente.last_name', ', ', 'derechohabiente.first_name', ' ', 'derechohabiente.middle_name')"), 'like', '%' . $search . '%')
->orWhere('derechohabiente.first_name', 'LIKE', "%{$search}%")
->orWhere('derechohabiente.middle_name', 'LIKE', "%{$search}%")
->orWhere('derechohabiente.last_name', 'LIKE', "%{$search}%")
->orWhereRaw("derechohabiente.rfc like '%$search%'");
});
});
users might search for names in various ways.
I hope it would work for you.

laravel5 Eloquent and Query builder

I'm trying to achieve something like the following:
"SELECT * FROM lists WHERE school_name LIKE '%" . $search . "%'"
Eloquent and Query builder
Thanks in advance.
$results = List::where('school_name', 'like', '%' . $search . '%')->get();
This assumes that you have a model called 'List' and a database table called 'lists'. If you do not have a model directly coupled, you could use the following query:
$results = DB::table('lists')->where('school_name', 'like', '%' . $search . '%')->get();
You can also only get the first result by using first() instead of get()
Here is the documentation describing the query builder:
https://laravel.com/docs/5.6/queries

Laravel 5.3 adding brackets to eloquent query that has orWhere clause and AND condition

I am obviously new to laravel, i am trying to build this query
select * from `users` where (`is_enumerator` is not null) and (`firstname` LIKE '%nai%' or `email` LIKE '%nai%' or `id` LIKE '%nai%' or `lastname` LIKE '%nai%' or `county` LIKE '%nai%' or `ward` LIKE '%nai%')
but this is what i'm getting
select * from `users` where (`is_enumerator` is not null) and `firstname` LIKE '%nai%' or `email` LIKE '%nai%' or `id` LIKE '%nai%' or `lastname` LIKE '%nai%' or `county` LIKE '%nai%' or `ward` LIKE '%nai%'
when using this eloquent query
Edit $query = Input::get('search-user'); //from the search box
if($query !='') {
$user = User::where(function ($query) {
$query->whereNotNull('is_enumerator');
})->where('firstname', 'LIKE', '%' . $query . '%')
->orWhere('email', 'LIKE', '%' . $query . '%')
->orWhere('id', 'LIKE', '%' . $query . '%')
->orWhere('lastname', 'LIKE', '%' . $query . '%')
->orWhere('county', 'LIKE', '%' . $query . '%')
->orWhere('ward', 'LIKE', '%' . $query . '%')
->get();
}
The brackets change the query completely, without them some users show up with the results from the search query. I have tried this link adding brackets in laravel query but it throws and error "builder cannot be converted to string error". I am sure its very simple i just cant find it. Thank you
You've actually done the right thing, just in reverse.
Right now, your query reads
WHERE (is_enumerator IS NOT NULL)
AND firstname LIKE '%...%'
AND email LIKE '%...%'
... and so on
So you put the first query in a function closure, when it should really be the second. :) Something like this.
$user = User::where(function ($q) use ($query) {
$q->where('firstname', 'LIKE', '%' . $query . '%')
->orWhere('email', 'LIKE', '%' . $query . '%')
->orWhere('id', 'LIKE', '%' . $query . '%')
->orWhere('lastname', 'LIKE', '%' . $query . '%')
->orWhere('county', 'LIKE', '%' . $query . '%')
->orWhere('ward', 'LIKE', '%' . $query . '%');
})
->whereNotNull('is_enumerator')
->get();
You can use this : User::where(function ($query) use ($variable){..
With the use ($variable) you are able to define a variabel to be used inside your query.
*variable is the variable you want to use

Resources