How to get records where column is not empty or null in laravel? - laravel

This is my table:
This is my code I tried:
$socials = SocialIcon::whereNotNull('link')->get()->all();
$socials = SocialIcon::whereNotNull('link')->get();
I want to get all records where column link is not empty.

First you have to understand the difference between NULL and an empty string. NULL is the absence of a value and no memory is allocated for NULL. But empty string is a value with value stored in the memory as "". From your db I can see you have an empty string as a value for the last row in link column. If the value is NULL then you will find NULL is written in the field.
Now as you want to check both NULL and empty you should write it like
$socials = SocialIcon::whereNotNull('link')->orWhere('link','<>','')->get();
this query will both check for NULL and empty value and will return rows with not NULL and empty link value.

Considering a value as NULL same as empty string is not correct. Both are not same.
You can use the below code:
$socials = SocialIcon::where(function($q) {
$q->whereNotNull('link')->orWhere('link','<>','');
})->get();
The resulted query running on DB will be:
select * from social_icons where (link is not null or link <> "")
If you wish to learn more about the Laravel's query builder, click here

You can simply do this
$socials = SocialIcon::where('link', '<>', '')->get();
Read this: https://laravel.com/docs/7.x/queries#where-clauses
Following will also do the job.
$socials = SocialIcon::all();
And then in your template for second case:
#foreach($socials as $social)
#if(!empty($social->link))
your content here
#endif
#endforeach

Related

OptionSetValueCollection not taking a null value. Throws Generic SQL error when setting up the value to null

I'm creating a new record in CRM plugin(by reading the data from a related record) and the data that I'm passing may / may not contain "OptionSetValueCollection". Whenever the value for the OptionSetValueCollection is null the IOrganization.Create is throwing a Generic SQL exception.
Currently I'm checking the submitted value for null and when not null I'm not submitting a value for the created object.
My question is why does OptionSetValueCollection not taking null? Is this a platform issue?
I've also tried creating a List<OptionSetValue> object and adding the incoming OptionSetValues from the OptionSetValueCollection and then passing it to the target attribute, tried passing in null and also used the null-coalescing operator all with no luck.
//Earlybound code
Account account = new Account(){
Name = newBrand,
new_accounttype = new OptionSetValue((int)new_AccountType.Brand),
TerritoryId = siteRequestRecord.new_territoryid,
new_category1 = siteRequestRecord.new_category1 ?? null,
};
if (category2 != null)
{
account.new_category2 = siteRequestRecord.new_category2;
}
service.Create(account);
Seems to be a long outstanding issue.
There is a bug related to multiselect optionset - if you set it to null during creation that will trigger an error. But the same code that sets field to null works fine during update.
So if you set it to null during Create just don't set field value and as a result you'll get blank value of a field.
If I understand you want to set Optionset to null. use below code it shall work and set null for your optionset
new_accounttype = null;

Linq where condition on datetime.ToString()

I have following Linq code
// query = IQueryable<DataClass>
query = query.Where(m => m.Column1.Contains(model.search.value)
|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value));
return query.ToList() // here the error is thrown
I get NullReferenceException error
Exception has occurred: CLR/System.NullReferenceException An exception
of type 'System.NullReferenceException' occurred in
Microsoft.EntityFrameworkCore.dll but was not handled in user code:
'Object reference not set to an instance of an object.' at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
if i commented out the line for 2nd column it works
//|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value)
model.search.value is string value I am trying to filter all columns. The DateTimeColumn2 is in DateTime datatype in the database, but user input string, therefore Iam converting DateTimeColumn2 to string and try to filter to users value. Any idea, what I am doing wrong ?
What happens here is that the part...
|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value)
...can't be translated into SQL (ToString("dd.MM.yyyy") isn't supported`), so EF-core auto-switches to client-side evaluation.
However, now the whole Where clause is evaluated client-side, including the first part,
m.Column1.Contains(model.search.value)
Now this first part has become susceptible to null reference exceptions. There are entities that have a null for Column1.
When you remove the DateTimeColumn2 predicate the whole statement can be translated into SQL and evaluated by the database.
It is likely that your DateTimeColumn2 can have NULL values which is very normal for DateTime columns. Also you shouldn't convert it to a string but the search value to a datetime. Is the user searching like "01" to mean any 1st date of any month and\year?
query = query.Where(m => m.Column1.Contains(model.search.value)
|| !m.DateTimeColumn2.HasValue
|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value));
return query.ToList()
If you think that the exception is thrown because of any of the DateTimeColumn2 values might be null, check for non-nullness:
query = query.Where(m => ...
|| (m.DateTimeColumn2 != null &&
m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value)));

Laravel query builder - Select elements unique or null on specific column

I have a model Form for table forms. There is a column called guid which can be null, or contain some sort of grouping random hash.
I need to select all forms that have column guid either null or unique in current search. In other words, for repeating guid values in current search I select only first occurence of every guid hash.
I tried:
$results = App\Form::where(... some where clauses .. ).groupBy('guid')
and it's almost ok, but for all rows, where guid == NULL it groups them and selects only one (and I need all of them).
How can I get the unique or null rows either by building proper SQL query or filtering the results in PHP?
Note: I need my $results to be an Illuminate\Database\Eloquent\Builder instance
EDIT:
I fount out that SQL version of query I need is:
SELECT * FROM `forms` WHERE .... GROUP BY IFNULL(guid, id)
What would be equivallent query for Laravel's database query builder?
UPDATE: Using DB::raw
App\Form::where(... conditions ...)
->groupBy(DB::raw("IFNULL('guid', 'id')"));
Or the another way could be:
You can also use whereNotNull, whereNull & at last merge both the collections using merge() like this:
First get the results where guid is grouped by (excluding null guid's here):
$unique_guid_without_null = App\Form::whereNotNull('guid')->groupBy('guid')->get();
Now, get the results where guid is null:
$all_guid_with_null = App\Form::whereNull('guid')->get();
and at last merge both the collections using merge() method:
$filtered_collection = $unique_guid_without_null->merge($all_guid_with_null);
Hope this helps!
For your edited question, you can use raw() as;
->groupBy(DB::raw("IFNULL('guid', 'id')"))
So your final query will be as:
$results = App\Form::where(... some where clauses .. )
->groupBy(DB::raw("IFNULL('guid', 'id')"));
By above query, your $results will be an instance of Illuminate\Database\Eloquent\Builder.

Filter a Laravel collection by date

In the code given below $allZip["assigned_date"] has value 2016-07-27 18:12:26. When I try to compare it with the created_at field which is a timestamp field as well, the result is an empty collection.
$filtered_datas = $datas->filter(function ($data) use($allZip) {
return $data->zip == $allZip["zip"] && $data->created_at < $allZip["assigned_date"];
});
There is data in database with zip field matching value from $allZip["zip"] and created_at field with value 2016-07-19 18:12:26. So it should return one item in the collection but returns an empty collection instead. Why?
Make sure that all your dates is DateTime or Carbon instances, not strings. Otherwise, comparison operator shouldn't working as you expected.

LINQ Query Result - dynamically get field value from a field name variable

LINQ newbie here
I am trying to get a value of a field - using a fieldName variable.
If I do a watch on row[FieldName] I do get a value - but when I do it on the actual code it will not compile.
string fieldName = "awx_name"
List<awx_property> propertyQry =
(
from property in crm.awx_propertyawx_properties
where property.awx_propertyid == new Guid(id)
select property
).ToList();
foreach (awx_property row in propertyQry)
{
//THIS DOES NOT WORK
fieldValue = row[fieldName];
}
Thanks in advance. Alternatives would be welcome as well
You keep us guessing what you are trying to do here... You need to specify the types of the objects, so it's easy for us to understand and help. Anyway, I think you are trying to get an object based on the ID. Since you are getting by Id, my guess would be the return value is a single object.
var propertyObj =( from property in crm.awx_propertyawx_properties
where property.awx_propertyid == new Guid(id)
select property
).SingleOrDefault();
if(propertyObj != null) {
fieldValue = propertyObj.GetType().GetProperty(fieldName).GetValue(propertyObj, null);
}
Of course, you need to add validation to make sure you don't get null or any other error while accessing the property value.
Hope it helps.
What type is fieldValue? What does awx_property look like? This will only work is awx_property is a key/value collection. It its not, you could use reflection instead.
If it is a key/value collection you are probably missing a cast. (row[FieldName].ToString() or something) Also you are missing a semi-colon in the foreach block.

Resources