eloquent relation in laravel with json - php

suppose i have two tables(Team and User) in my database . in Team table i have data like "["5","6","7","9","10","26","27"]"(json) , and in users table i have id column in which data is like serial no(Auto_increment .1,2,3 ....nth).is it possible a relation which finds a if json has that single key in it.
i have a loop statement which has the result that i want but i want that data in relation the code is :
foreach($model as $key => $value){
$user_data = User::whereIn('id',json_decode($value->member_ids))->get();
$model[] = $user_data;
}

Try this
$arr = json_decode("["5","6","7","9","10","26","27"]");
if (in_array(5, $arr )) {
// code
}

Related

Laravel: Querying JSON column containing array, expecting similar results to "whereIn"

I have a database column called support_tags. This is a jsonb column containing a simple array that looks like:
[
"caring",
"budgets",
"careers_employment",
"addictions"
]
I am attempting to query this column using the following:
$services = \App\Models\Service::where("status", "accepted")->whereRaw("JSON_CONTAINS(support_tags, '" . json_encode($categories) . "')")->get();
This doesn't retrieve the results I am hoping for/expecting. If I send the following array:
[
"caring",
"smoking"
]
The results I get back are services that contain all array elements. I need this to work more like a whereIn, in that not all array values need to be present in the database column, but one or more. If anyone knows of a way to do this I'd be very grateful. Thanks.
you can use these eloquent methods: ->whereJsonContains() and ->orWhereJsonContains()
your query will be like this:
$services = \App\Models\Service::where("status", "accepted")
->where(function($query) {
$query->whereJsonContains('support_tags', 'smoking')
->orWhereJsonContains('support_tags', 'caring');
});
Just before I accept the other answer to this question, I thought it may be useful to share my implementation of this which is based on the accepted answer This does the trick:
$categories = request()->infoAdviceCategories;
$services = [];
if (count($categories)) {
$services = \App\Models\Service::where("status", "accepted")->whereJsonContains("support_tags", $categories[0]);
foreach ($categories as $category) {
if ($category !== $categories[0]) {
$services->orWhereJsonContains("support_tags", $category);
}
}
$services = $services->get();
}
return $services;

How can i update one row usign two keys in laravel?

I have a need to update a table like this :
UPDATE table SET column = value WHERE first_id = 1 AND second_id = 2
Is it possible to do this in Laravel using eloquent model? If it is how can i do this?
I was trying with :
$object = Model::where('first_id' , 1)->where('second_id' , 2)->get();
$object->column = $value
$object->save();
Yes you can do it. Here is how you can do it.
Model::where('first_id', 1)
->where('second_id', 2)
->update(['column' => 'yourValue']);
You are getting a collection. You can update the column of each of those collection. You can only get the first one collection using first.
foreach($object as $obj){
$obj->column = $value;
$obj->save();
}
Or
$object = Model::where('first_id' , 1)->where('second_id' , 2)->first();
$obect->column =$value;
$object->save();

How to find and merge two rows into one

I am new to Laravel so I am confused how to do this
I have a table called groups where I forget to use unique in validation . After Long time I found out there are multiple datas with same name for ex :
I have two datas with same name called Feminism but with different id
The group table have only name and description columns , but it has relation with products many to many I have other datas too which has same name I want to merge those datas into one . along with the relation to the product . Is is possible ?
Shall I have to check all the names manually like
Item::where('name','Feminism')->get();
and then merge those datas or we have some other relavant methods
You can refactor this code for your models and relations
foreach ($groups as $group) {
$duplicates = Group::where('name', $group->name)->where('id', '<>', $group->id)->get();
foreach ($duplicates as $duplicate) {
$mustBeUpdatedRelation = $duplicate->products;
$anotherRelation = $duplicate->anotherRelation;
foreach ($mustBeUpdatedRelation as $product) {
$product->categories()->detach($duplicate->id); // if product has pivot data you must get these and assign to new relation
//new relation
$product->categories()->attach($group->id);
}
$anotherRelation = $duplicate->anotherRelation;
foreach ($anotherRelation as $item) {
// like above
// detach duplicated
// attach unique
}
//finally you can delete or .... duplicated group
$duplicate->update([
'name' => "duplicated_$duplicate->name"
]);
}
}
You may use the following
$items = App\Item::with('products')->get();
$tempArr = [];
foreach ($items as $key => $item) {
if(isset($tempArr[$item->name])) {
$merged = $tempArr[$item->name]['products']->merge($item->products);
unset($tempArr[$item->name]['products']);
$tempArr[$item->name]['products'] = $merged;
} else {
$tempArr[$item->name] = $item;
}
}
foreach ($tempArr as $item) {
$item->products()->sync($item->products->pluck('id'));
}
$idsToKeep = array_column($tempArr, 'id');
App\Item::whereNotIn('id', $idsToKeep )->delete();
Use onDelete cascade when defining your pivot table migration.
This takes care of deleting the model’s relations for you:
e.g.
$table->foreign(’item_id’)
->references(’id’)->on(’items’)
->onDelete(’cascade’);

Laravel 5.4 get only 2 column data from db as array key and value

db column screenshot
I want to fetch only two columns data from table 1st column data as array key and another column data as array value.
as array['wid'=>'temp']
result should be array['1'=>'1.5','2'=>'11.50']
for laravel 5.4
You could use the pluck() method (scroll down to the Retrieving A List Of Column Values) e.g.
$data = DB::table('city_list')->pluck('city_name', 'cid');
Use Collection pluck() The pluck method retrieves all of the values for a given key:
$data = DB::table('city_list')->pluck('city_name','cid');
For more information visit laravel doc here
This worked for me.
$data = DB::table('city_list')->select('cid','city_name')->get();
$val = array();
foreach ($data as $key => $value) {
$val[$value->cid]=$value->city_name;
}

what is a good way to save an array data to mySQL in laravel

Its an online result marker. Once the user clicks save it gets the CA(Continious assessment) and it gets the Exam marks and the teachers remark for the particular student. I want to know how i can insert these fields into my database the right way.
return $request->all();
the above code returns the image below
$i = 0;
foreach($request->id as $id) {
$model = new Model;
$model->user_id = $id;
$model->ca_mark = $request->ca_mark[$i];
$model->exam_mark = $request->ca_mark[$i];
$model->remarks = $request->remarks[$i];
$model->save();
$i++;
}
Query Builder
$i = 0;
foreach($request->id as $id) {
DB::table('table')->insert([
'user_id' => $id,
'ca_mark' => $request->ca_mark[$i],
'exam_mark' => $request->ca_mark[$i],
'remarks' => $request->remarks[$i]
]);
$i++;
}
The above code has been written based on an assumption of the database table structure. In short, foreach on the ID's as this would be the student ID, and take the ca_mark, exam_mark and remark based on the key of the id.

Categories