How to use Ardalis Specification with ValueObject and HasConversion - value-objects

Let's say I use a ValueObject for a ZipCode, and I have a Converter to save it as a string in the database.
// EntityTypeConfiguration
builder.Property(p => p.ZipCode)
.HasConversion<ValueOfConverter<ZipCode, string>>()
.HasMaxLength(PostalCodeMaxLength)
.IsRequired();
When I'm doing a search, I have to cast like this or else I get and exception
// Query
Query.Search(x => (string)(object)x.ZipCode, zipCode);

Related

Retrieve specific data using JSON decode Laravel

I'm new to Laravel. I need to retrieve specific data from the database using the JSON decode. I am currently using $casts to my model to handle the JSON encode and decode.
This is my insert query with json encode:
$request->validate([
'subject' => 'required|max:255',
'concern' => 'required'
]);
$issue = new Issue;
$issue->subject = $request->subject;
$issue->url = $request->url;
$issue->details = $request->concern;
$issue->created_by = $request->userid;
$issue->user_data = $request->user_data; //field that use json encode
$issue->status = 2; // 1 means draft
$issue->email = $request->email;
$issue->data = '';
$issue->save();
The user_data contains {"id":37,"first_name":"Brian","middle_name":"","last_name":"Belen","email":"arcega52#gmail.com","username":"BLB-Student1","avatar":"avatars\/20170623133042-49.png"}
This is my output:
{{$issue->user_data}}
What I need to retrieve is only the first_name, middle_name, and last_name. How am I supposed to achieve that? Thank you in ADVANCE!!!!!
As per the above code shown by you it will only insert data into the database.For retrieving data you can make use of Query Builder as i have written below and also you can check the docs
$users = DB::table('name of table')->select('first_name', 'middle_name', 'last_name')->get();
I will recommend using Resources. It really very helpful laravel feature. Check it out. It is a reusable class. You call anywhere and anytime.
php artisan make:resource UserResource
Go to your the newly created class App/Http/Resources/UserResource.php and drfine the column you want to have in your response.
public function toArray($request) {
return [
"first_name" => $this->first_name,
"middle_name" => $this->middle_name,
"last_name" => $this->last_name
]
}
Now is your controller you can use the UserResource like folow:
public function index()
{
return UserResource::collection(User::all());
}
Or after inserting data you can return the newly added data(f_name, l_name...)
$user = new User;
$user->first_name= $request->first_name;
$user->middle_name= $request->middle_name;
$user->last_name= $request->last_name;
$user->save();
$user_data= new UserResource($user);
return $user_data;

Issues trying to access an associative array converted from JSON in Laravel

I'm working on a Laravel project that implements react-jsonschema-form and I need to convert the values saved in the database to an associative array so I can pluck certain values from it. However I am getting strange results when doing so.
Here is the code I use to grab the JSON data from the table and then convert to an array:
$form = Form::where('id', $formId)->get();
$converted = json_decode($form[0]->form_data, true);
$formArray = print_r($converted, 1);
return $formArray;
For testing purposes I am simply rendering the data in the browser.
The result from the above return is:
Array
(
[1] => Array
(
[1.1] => New
[1.2] => Ms
[1.3] => Isobel Fleming
[1.4] => Array
(
[uprn] => 52375918
[address_1] => Fake Street
[address_2] =>
[address_3] =>
[town_city] => BRISTOL
[postcode] => BS1 3KE
)
[1.5] => 0129711011
[1.6] => 0800999111
[1.7] => 0781100022
[1.8] => isobelfleming#jourrapide.com
)
)
which is great. However when I try and access anything from it like:
return $formData[1][1.1]
I get:
String offset cast occurred
If I try using a string:
return $formData[1]['1.1']
I get:
Illegal string offset '1.1'
So I am not sure what to do to access this data. The problem is, although it's not ideal to have the associate keys with decimals in them, this is the way the schema is set up and it's several thousand lines long - this is just a snippet of the form data.
Is there anything that can be done in order to get the data from this array?
I figured it out. It seems like the following line was the problem:
print_r($converted, 1);
It didn't need to be printed as an array, I should have just used the $converted variable to access the data like so:
return $converted[1]['1.1'];

Intersect or Except methods in linq not working in MYSQL

I am using entity framework with mysql. I have to use Intersect in one of the query but it throws the error "Specified method is not supported.". Can anyone suggest alternatives other than taking data to memory and apply Intersect on that.
public List<share> GetFeed(List<long> UserRules, List<long> ListedShares, string AuthorID)
{
List<share> listshare = DbContext
.shares
.Where(x => UserRules.Intersect(x.share_rules.Select(y => y.rule_id)).Any())
.ToList();
return listshare;
}
Specified method is not supported. means that EntityFramework is not able to translate it to SQL query. Actually, in most cases, it is possible to convert it to Contains, which is supported. You should change your method to match:
public List<share> GetFeed(List<long> UserRules, List<long> ListedShares, string AuthorID)
{
List<share> listshare = DbContext
.shares
.Where(x => x.share_rules.Any(y => UserRules.Contains(y.rule_id)))
.ToList();
return listshare;
}

Inserting JSON to DB Using Model in Laravel

I'm trying to use the model create option and this is my array:
$result = array(
'match_id' => $input['id'],
'score' => $input['score'],
'result' => $input['result'],
'headline' => NULL,
'article' => $input['report'],
'tries' => $input['try'],
'try_amount' => $input['tryquant'],
'conversions' => $input['conv'],
'conv_amount' => $input['convquant'],
'penalties' => $input['pens'],
'pen_amount' => $input['penquant'],
'dropgoals' => $input['dgs'],
'dg_amount' => $input['dgquant']
);
Result::create($result);
The contents of some of these are arrays themselves. eg:
$input['penquant'] = [
"4"
]
When I run my code, it saves the data to the DB simply as Array and throws up the following error:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
Can someone tell me what I'm doing wrong and how to fix it?
Shouldn't have rushed, forgot to use json_encode.
The best is to use mutators and accessors in your model.
example of mutator
// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it
// into the database
public function setPenAmountAttribute($value)
{
$this->attributes['pen_amount'] = serialize($value);
}
example of an accessor is
// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
return unserialize($value);
}
You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.

Help building up LINQ query when using anonymous types

I've started out with:
IQueryable<Author> authors2 = db.Authors;
Then I build up authors2 in multiple if statements, here's one of them
authors2 = authors2.Where(t => t.ItemAuthors.Any(b => b.Item.CategoryItems.Any(z => z.categoryID == int.Parse(ddlCategory.SelectedValue))));
Then finally I would like to append this to the end of the built up where clauses
authors2.OrderBy(x => x.text).Select(x => new
{
authorText = string.Format("{0} ({1})",x.text, x.ItemAuthors.Count())
});
To bind a control like this:
ddlAuthor.DataSource = authors2;
ddlAuthor.DataTextField = "authorText";
ddlAuthor.DataBind();
Apparently the compiler is not very happy about my select new statement. How can I rewrite this to achieve the same goal? I believe this is called creating an anonymous type.
It says an explicit conversion exists(are you missing a cast?) I can't figure out how to cast it.
In your third statement, the returned type is not same as authors2 because the Select projects a different type other than Author
So assign the value to a new variable
var authorsFinal = authors2
.OrderBy(x => x.text)
.Select(x => new
{
authorText = string.Format("{0} ({1})",
x.text,
x.ItemAuthors.Count())
});