I am finding that I often need to select a field, based on a condition other than the id.
So, $user = User::where('last_login', $lastLogin)->where('last_warning', $lastWarning)->get(); works perfectly.
That is until you set one of the where's to allow nulls (let's do last_login).
That is, it can either have a value or be null.
That means you need to use one of two function where() or whereNull() and to do that you need to break the chain, so it becomes
$user = User::where('last_warning', $lastWarning);
is_null($lastLogin) ? $user->whereNull('last_login') : $user->where('last_login', $lastLogin);
$user = $user->get();
I am wondering if where has a way to deal with this? as currently if you pass null through to where you get where column = null which doesn't work!
Two options:
Option 1:
if (is_null($lastLogin))
{
$user = User::whereNull('last_login')->where('last_warning', $lastWarning)->get();
}
else
{
$user = User::where('last_login', $lastLogin)->where('last_warning', $lastWarning)->get();
}
Option 2:
$user = User::where('last_login', (is_null($lastLogin) ? 'IS' : '=') ,$lastLogin)->where('last_warning', $lastWarning)->get();
Option two makes the query 'where last_login = x' or 'where last_login IS null'
You can try this:
User::where(function($query) use ($lastlogin)
{
if(is_null($lastLogin))
{
$query->whereNull('last_login');
}
else
{
$query->where('last_login', '=', $lastLogin);
}
})->get();
It is a good solution when dealing with long queries with more than one parameter.
You can use DB::raw() as well:
User::where('last_login', 'IS', DB::raw('null'))->where_last_warning($lastWarning)->get();
As of Laravel 5.3 you are now able to ->where('column', null) to automatically produce WHERE column IS NULL.
If using variable, make sure that they have PHP null strict value.
Related
Hi i am having troubles sorting this out as the title says i am trying to check if a record exist and return a boolean instead of the record value from the database so i can compare it with a filter form, i know this can be solved using nested if's but i'm trying to find a better way, this is my code so far
public function getSend(){
if($this->request->role==1){
$id= Cv::select('cv.user_id','cv.pub')
->where('cv.pub','==',$this->request->pub)
->get();
dd($id);
return view('gestione.'.$this->view_namespace.'.send.pagina');
}
my idea is something like this
->where('cv.pub','==',$this->request->pub)
this one works because "pub" stores a boolean record in my database alot of other records store strings for example
->where('cv.something','==',$this->request->something)
wouldnt work because "something" is a string and not a boolean so how do i turn "something" into a boolean based on if wheter exist or not
thanks in advance by the way i am using laravel 5.1
Try this,
->where('cv.something','==',!empty($this->request->something))
$something = !empty($this->request->something);
if($something) {
$exits = Cv::where('cv.'+$something, $something)->get();
if($exits) {
// Cv exits
}
}
You may try something like this:
$id = Cv::select('cv.user_id','cv.pub') // select is not required here
->where('cv.pub','==',$this->request->pub)
->exists();
Also, you may use it like:
if (Cv::where('cv.pub', $this->request->pub)->exists()) {
// The record exists, so do something...
}
This query will return a boolean true if exists, otherwise false. You may also make the query conditionally depending on the $this->request->pub in one go, for example:
$exists = Cv::when($this->request->pub, function($query) {
$query->where('cv.pub', $this->request->pub);
})->exists();
if ($exists) {
// ...
}
$result = Cv::select('cv.user_id','cv.pub')
->where('cv.pub','==',$this->request->pub);
if($request->something){
$result = $result->whereNotNull('cv.something'); // or != '', depending how you store it
}
This is mostly how filters works
If you want to return a boolean you can use count() :
$id= Cv::select('cv.user_id','cv.pub')
->where('cv.pub','==',$this->request->pub)
->count();
This will return the number of records, 0 if none, 1 if one is found. Obviously this will only work if 1 record is found, if 3 are found this solution wont work however I from what you have said it seems like that is all you will return.
Anything more than 0 means that a value exists.
This is my code to filter values based on parameters. I want to move it into to a single line. Is there any option available in laravel4?
if($network) //when $network variable has a value.(i will have the same thing for orderby, customer, etc..)
{
return $deals=$mobiles->deals()->where('network','=',$network)->get();// ->orderby($orderby);
}
else
{
return $deals=$mobiles->deals()->get();
}
Go with a ternary:
return $network ? $mobiles->deals()->where('network','=',$network)->get() : $mobiles->deals()->get();
A more clean way than ternary suggested by #moonwave99 (in my opinion) is to add a scope to your model.
public function scopeNetwork($query, $network = null) {
if (null !== $network)
$query->where('network', $network);
return $query;
}
You can then use
return $mobiles->deals()->network($network)->get();
This is an incredibly round-about way of doing this... Id recommend #moonwave99's solution, but you can pass a closure to where(). That, mixed with a boolean, and whereNotNull() can do it. Technically, it's one line of code, but I've broken it apart for the sake of readability.
Easy way:
return $network ? $mobiles->deals->where('network',$network)->get() : $mobiles->deals->get();
Overly complicated way:
return $mobiles->deals->where(isset($network) ? function($query) use ($network){
$query->where('network', $network);
} : function($query){
$query->whereNotNull('id');
})->get();
Im wondering why nobody suggested to use LIKE instead of =. I did like this, and works very well.:) I can have very dynamic filtering with many fields. Make sure the variable in where is set to null when you want to return all element.
My code become
$sorttype=$orderby[0]=='-'?"desc":"asc"; //To get based on assenting or dissenting order
$orderby=$orderby[0]=='-'?substr($orderby, 1):$orderby; //just removing the first element if - existing, because that is just a flag.
if(!$network){$network=null;} //set to null
if(!$orderby){$orderby='id';} //set to id when there no order by
return $deals=$mobiles->deals()
->where('network','LIKE',$network)
->orderby($orderby,$sorttype)
->get();
I'm using Laravel 4. Say I have an Eloquent model (Patient) and I want to get a patient with the name Bob, I would do this:
$patient = Patient::where('name', '=', 'Bob');
What is the best way to check to see if $patient is a valid record?
If the database query does not find any matching results, it returns null. Therefore...
$patient = Patient::where('name','=','Bob')->first();
if ( is_null($patient) ) {
App::abort(404);
}
(Note: in your original question you forgot ->first() (or ->get()) in your query. Don't forget that or else you will get an Eloquent object instead of a result.)
use this:
$patient = Patient::where('name', '=', 'Bob')->firstOrFail();
it will return Eulqouent model on success or throw ModelNotFoundException upon failure.
I know this is old, but this came up as the 2nd google hit on a search, so . . . for cases where you are not expecting one record or cannot use ->firstOrFail() (my use case is an async typeahead api that returns up to 10 results) the only thing that worked for me was count():
$patient = Patient::where('name', '=', 'Bob')->get(); //you could have more than one bob
if (!count($patient)) {
return 'No records found';
}
$patient = Patient::where('name','Bob')->get();
if ( $patient->isEmpty() ) {
return response(['error' => 'Record not found'], 404);
}
Something like Patient::where('name', '=', 'Bob')->exists() may work. It will return a boolean.
Just use empty() from native php will solve everything, if object null it will return true, if laravel's collection from query builder is empty (but initialized) it will return true too.
$contributor = Contributor::whereVendor('web')->first();
if(empty($contributor)){
...
}
use findOrFail($id) in case of you are passing id parameter to fetch a single record
I ended up on this while seeking solution of ::find($id)->firstOrFail syntax which is error-full.
$patient = Patient::findOrFail($id);
I have some table store_section(id,parent_id,label), I want to change some row, set parent_id=null.
I trying to:
$record = $table->getTable()->find( $id );
$record->parent_id = null;
$record->save();
But this isn't work. How can I do set NULL into the table in Doctrine, in example above, parent_id becomes =0 (not =NULL)?
Thnx for the responses!
I would try one of the following:
1:
$record = $table->getTable()->find( $id );
$record->parent_id = new Doctrine_Null();
$record->save();
2:
$record = $table->getTable()->find( $id );
$record->parent_id = "NULL";
$record->save();
I have not tested these, but I do recall having a similar issue prior, just cannot recall how I solved it. Hope this helps!
You can use method set('u.name', 'NULL')
For example:
Doctrine_Query::create()->update('User u')->set('u.name', 'NULL')->where('u.id = ?',$id);
Doctrine_Null only has two methods, and the one that seems to relate is the __toString method. So in order to activate the magic method you need to cast as a string:
$record = $table->getTable()->find( $id );
$record->parent_id = (string) new Doctrine_Null;
$record->save();
But honestly there is no reason, as Doctrine_Null just abstracts an empty string ''. I can only assume that it only works in this scenario because parent_id is not enforcing a NULL attribute.
Setting a value of 'NULL' appears to work but is actually a string and not NULL.
'NULL' !== null
Give it a shot, if you insert 'NULL' into one row, and another row is a "natural NULL", and you pull both rows out of the table and do a var_dump(serialize()) on each, you will see one is a natural null and other is actually a string.
If you want to maintain consistency and enforce natural nulls, use this instead:
$record = $table->getTable()->find( $id );
$record->parent_id = new Doctrine_Expression('NULL');
$record->save();
in this case, when the field is a relation. I have complished this task with:
$record->Parent = null;
$record->save();
Above Parent is the relation name.
In Doctrine2 Using the query builder, you can also directly update the value in the db.
$qb = // $this->connection->createQueryBuilder(); or $this->em->createQueryBuilder();
$qb->update('store_section', 's')
->set('s.parent_id', ':parent_id')
->andWhere('s.id', ':id'));
$qb->setParameter('parent_id', null);
$qb->setParameter('id', $id);
$qb->execute();
$record->setParentId(null);
$record->save();
I'm using CodeIgniter's Active Record class to query the MySQL database. I need to select the rows in a table where a field is not set to NULL:
$this->db->where('archived !=', 'NULL');
$q = $this->db->get('projects');
That only returns this query:
SELECT * FROM projects WHERE archived != 'NULL';
The archived field is a DATE field.
Is there a better way to solve this? I know I can just write the query myself, but I want to stick with the Active Record throughout my code.
where('archived IS NOT NULL', null, false)
The Active Record definitely has some quirks. When you pass an array to the $this->db->where() function it will generate an IS NULL. For example:
$this->db->where(array('archived' => NULL));
produces
WHERE `archived` IS NULL
The quirk is that there is no equivalent for the negative IS NOT NULL. There is, however, a way to do it that produces the correct result and still escapes the statement:
$this->db->where('archived IS NOT NULL');
produces
WHERE `archived` IS NOT NULL
CodeIgniter 3
Only:
$this->db->where('archived IS NOT NULL');
The generated query is:
WHERE archived IS NOT NULL;
$this->db->where('archived IS NOT NULL',null,false); << Not necessary
Inverse:
$this->db->where('archived');
The generated query is:
WHERE archived IS NULL;
Null must not be set to string...
$this->db->where('archived IS NOT', null);
It works properly when null is not wrapped into quotes.
Much better to use following:
For is not null:
where('archived IS NOT NULL', null);
For is null:
where('archived', null);
And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.
Codeigniter generates an "IS NULL" query by just leaving the call with no parameters:
$this->db->where('column');
The generated query is:
WHERE `column` IS NULL
$this->db->or_where('end_date IS', 'NULL', false);
You can do (if you want to test NULL)
$this->db->where_exec('archived IS NULL)
If you want to test NOT NULL
$this->db->where_exec('archived IS NOT NULL)
If you are using multi where in your model like:
function getCommonRecords($id, $tbl_name, $multi_where='') {
$this->db->select('*');
$this->db->where('isDeleted', '0');
if ($id > 0) {
$this->db->where('id', $id);
}
if ($multi_where != '') {
foreach ($multi_where as $key => $val) {
$this->db->where($key, $val);
}
}
$queryResult = $this->db->get($tbl_name);
return $queryResult->result_array();
}
Then I would recommend using the following syntax that will bypass the second parameter in calculating the multi where condition.
$this->api->getCommonRecords(NULL,'contracts', ['id' =>,'party1Sign IS NOT NULL'=>NULL,'party2Sign IS NOT NULL'=>null]);
One way to check either column is null or not is
$this->db->where('archived => TRUE);
$q = $this->db->get('projects');
in php if column has data, it can be represent as True otherwise False
To use multiple comparison in where command and to check if column data is not null
do it like
here is the complete example how I am filter columns in where clause (Codeignitor). The last one show Not NULL Compression
$where = array('somebit' => '1', 'status' => 'Published', 'archived ' => TRUE );
$this->db->where($where);