Laravel Query Where Relationship within Relationship Condition - laravel

Been trying to resolve this query for a long time now, it's working but there is a bit of misquery.
This is one of my queries from my search function with livewire.
return empty($search)
? static::query()
: static::query()->where('id','like','%'.$search.'%')
->orWhereHas('status.user',function($q) use ($search){
$q->where('active',1)
->where('name','like','%'.$search.'%')
->orWhere('username','like','%'.$search.'%');
});
For example, I type the name of 'jason' the query will return the correct result, but if I type Jason's username it will return every record that Jason's been update (but not active) I just want the action to return with a particular name or username.
I already try to separate the active, name, and username on different functions but the result is the same.

AND has precedence over OR so this condition
$q->where('active',1)
->where('name','like','%'.$search.'%')
->orWhere('username','like','%'.$search.'%');
is evaluating like - where ( active = 1 and name like '%$search%' ) or username like '%$search%'
But if I am not wrong then your want something like where active = 1 and ( name like '%$search%' or username like '%$search%')
To achieve this you can try segregating above condition like -
$q->where('active',1)
->where(function($q2) use ($search){
$q2->where('name','like','%'.$search.'%')
$q2->orWhere('username','like','%'.$search.'%');
});
Please let me know if it worked.

Related

Laravel relationship gives me "?" instead of email

I'm setting this relationship
public function nonAcceptedContracts()
{
return $this->belongsToMany(UserContract::class, 'invite', 'email', 'usercontract')->where('status', 'pending');
}
And calling it like that.
$user->loadMissing('nonAcceptedContracts');
dd($user->nonAcceptedContracts()->toSql());
What I get is
"select * from `usercontract` inner join `invite` on `usercontract`.`id` = `invite`.`usercontract` where `invite`.`email` = ? and `status` = ? and `usercontract`.`deleted_at` is null"
The query seems to be the one I'm looking for but why do I get this question mark there? Shouldn't be there the email of my user model? Also the "status" value, should be "pending" and there is another question mark.
That's just how toSql() works. What you are seeing is a parameterized query. These parameterized queries allow type-specific value when replacing the ? with their respective value. They are frequently used when executing dynamic SQL from a program.
You can read more on this topic here: https://scotch.io/tutorials/debugging-queries-in-laravel
If you really want to see the actual queries, try enabling the query log. One thing to note here is that this logfile can grow very large on a busy server.

Laravel update query use

I used this query to update the status column.
$val="1";
vehicles::where('id' , '=' , $veh_status)->update(['status' => $val]);
But when I submitted the status value doesn't change.
you can trace your query by using ->toSql() method !
try this to find whats happening in back
Not sure what the problem is there because you haven't given much info to work with, but you can check these suggestions:
Check if the column is set to be mass assignable in the model class, that is, it is in the fillable[] array.
make sure the id you pass to the where() function is valid.
Try using another function, save() which will achieve the same results you seek, like this;
// filter the vehicle
$vehicle = vehicles::where('id', '=', $veh_id)->first();
or
$vehicle = vehicles::find($veh_id);
$vehicle->status = 1;
$vehicle->save();
Lastly, I noticed your id variable you pass to the where the () function is called $veh_status "presumably - vehicle status" and not $veh_id, "presumably - vehicle id" so probably check that out.
Ref: Laravel Model Update documentation

For table cmdb_rel_ci, I want to retrieve unique parent.sys_class_name with count for "type=In Rack::Rack contains"

For table cmdb_rel_ci, I want to retrieve unique parent.sys_class_name with count for "type=In Rack::Rack contains". I am doing practice in out of the box instance.
At table level URL is as below:
URL
I want to retrieve result from above URL with my below script.
var count = new GlideAggregate('cmdb_rel_ci');
count.addQuery('type','e76b8c7b0a0a0aa70082c9f7c2f9dc64');// sys_id of type In Rack::Rack contains e76b8c7b0a0a0aa70082c9f7c2f9dc64
count.addAggregate('COUNT', 'parent.sys_class_name');
count.query();
while(count.next()){
var parentClassName = count.parent.sys_class_name.toString();
var parentClassNameCount = count.getAggregate('COUNT','parent.sys_class_name');
gs.log(parentClassName + " : " + parentClassNameCount );
}
The issue is I am getting parentClassName empty.
Try this instead:
var parentClassName = count.getValue("parent.sys_class_name")
Since it's a GlideAggregate query (instead of GlideRecord), the query being issued isn't returning all of the fields on the target table. With GlideRecord, dot-walking through a reference field (e.g. parent.sys_class_name) automatically resolves that referenced record to provide access to its field values. This is made possible by the fact that the driving/original query brought back the value of the parent field. This is not happening with GlideAggregate. The query in this case basically looks like:
SELECT cmdb1.`sys_class_name` AS `parent_sys_class_name`, count(*)
FROM (cmdb_rel_ci cmdb_rel_ci0 LEFT JOIN cmdb cmdb1 ON cmdb_rel_ci0.`parent` = cmdb1.`sys_id` )
WHERE cmdb_rel_ci0.`type` = 'e76b8c7b0a0a0aa70082c9f7c2f9dc64'
GROUP BY cmdb1.`sys_class_name`
ORDER BY cmdb1.`sys_class_name`
So, you actually have access specifically to that dot-walked sys_class_name that's being grouped, but not through the dot-walk. The call to getValue("parent.sys_class_name") is expectedly resolved to the returned column aliased as parent_sys_class_name.
That being said, what you're doing probably should also work, based on user expectations, so you've not done anything incorrect here.

Select Md5 combination of 2 rows from mysql

I have md5 some of the user information (lets say id and email for simplicity) and would like to use those information to find that user in my database.
The code in it's simplest form looks something like this
return $this->db->get_where('table', array('MD5(id,email)='=>$token ) ,1);
Not sure why but its returning false;
Update: trying to do this in sql
Just found out in when i try to do this in mysql I get an error
#1582 - Incorrect parameter count in the call to native function 'md5'
Is this mean you cant md5 multiple rows ? if so how do I do this!
Update: Again it returns false
$this->db->select('md5(id,email) as token');
$this->db->where('token', $token);
$this->db->limit(1);
$result = $this->db->get('table->customers');
Try concat in the where clause.
$this->db->where("md5(CONCAT(id,email)) = '".$token."'");

Get permission data from Database

I'm having problems to do a simple permission system on my Webapp. My DB has a table called "usuario" that has informations about the users of the system. One of these columns is called "privilegio" that has value '0' for administrators and 1 for regular users. An administrator has the power to Add and edit users on the system. Im trying to take this behavior querying my database with the cod of the logged user and getting its permission. If the user is not on the administrator group (privilegio=1) then the add/edit/delete buttons will be unset.
public function usuario() {
if($this->session->userdata('logged')){
$crud = new grocery_CRUD();
$crud->set_subject("Usuário");
$crud->set_theme('datatables');
$crud->set_table("usuario");
(...)
$crud->field_type('privilegio','dropdown',array('0'=>'Administrador','1'=>'Usuario'));
(...)
$this->db->select('privilegio');
$this->db->get('usuario');
$result = $this->db->where('cod_func',$this->session->userdata('cod_func'));
if(!$result){
$crud->unset_add();
$crud->unset_edit();
$crud->unset_delete();
}
(...)
The problem (and the question) is that this code only list the user that is logged on, not the others already registered on the system and stored on "usuario" table. I wonder that the list is been made by my query (what is not the behavior I would like) I hope you could undestand my doubt. Sorry for my bad english.
Thank you!
you're having trouble with the active record functions...
When you use the function
$this->db->get('usuario');
This translates to the query:
SELECT * FROM usuario
So try changing your code to something like this:
$this->db->select('privilegio');
$this->db->from('usuario');
$this->db->where('cod_func',$this->session->userdata('cod_func'));
$this->db->limit(1); //You're only expecting one result
$result = $this->db->get(); // Save the result to the variable result
//Edited for the comment, something like
$result = $result->first_row('array'); //Here I'm fetching only the first row into an array
$privilegio = $result['privilegio']; //Im saving the result from the query in the variable $privilegio
This translates to:
SELECT priviliegio FROM usuario WHERE cod_func = 'some_value' LIMIT 1;
Then you can do whatever you want with the $result variable, please refer to documentation to see what you can do...
Generating Query Results

Resources