I want to update pivot table in laravel 8 .I'm trynig sync method, but only insert first item of an array.
Here is my code
foreach ($products as $product) {
$quantity = $product['quantity'];
$product_id = $product['product_id'];
$food_item_price = FoodItemPrice::where('food_item_id', $product_id)->first();
$order->orderFoodItems()->sync([$product_id => [
'quantity' => $quantity,
'food_item_price_id' => $food_item_price->id,
]]);
}
In $products may have many products, but with sync method, it only updates first product. How to update pivot table properly?
Related
I passed my formData object via Ajax into laravel controller that have "pic[]" which contain an array of uploaded images, and "desc[]" which contain an array of descriptive text that related to the corresponding index for each image on the pic[] array.
Normally, when I want to insert it into the database, I would do this
if ($request->hasFile('pic')) {
foreach($request->pic as $p)
{
$myRow = tableName::create([
'picture' => $p
]);
};
};
But now that I want to insert the picture description into the same row that I just created, nested loop surely won't work, and I'm not sure how to do it with double loop for the desc array.
If you have desc[] like: [0 => 'First', 1 => 'Second', ...], you can access index of description if is equal to index of picture.
foreach($request->pic as $index => $p)
{
$myRow = tableName::create([
'picture' => $p,
'description' => $request->desc[$index] // also try $request->get('desc.' .$index)
]);
};
I hope it was helpful. Good luck.
Follow this code to insert an image in your database by using ajax
foreach($request->pic as $index => $p)
{
$myRow = tableName::create([
'picture' => $p,
'description' => $request->desc[$index] // also try $request->get('desc.' .$index)
]);
};
I hope it was helpful to you.
I am facing an issue is, i have to select a record from database with specific condition (where status=0), after that if around 20k rows are coming from select query then i added foreach loop to apply some conditions and on condition true i update the status of every fetched row from 0 to 1 and 1 to 2 and so on...
My problem is when large amount of data is coming from database then this process is hang and service stopped.
Please guide me what else i can do on place of foreach...if..else etc...
Use hash insted of foreach
// Common Usage:
$users = [
['id' => 1, 'name' => 'mark'],
['id' => 2, 'name' => 'jane'],
['id' => 3, 'name' => 'sally'],
['id' => 4, 'name' => 'jose'],
];
$results = Hash::extract($users, '{n}.id');
// $results equals:
// [1,2,3,4];
I am struggling with foreaching grouped records.
It is a collection of hours saved with the same date, and I want to group them in my view/output.
Any suggestions? I have tried a ton of different approaches. Here is how I get them from DB. (date = type date in mysql "Y-m-d"). And outputting them normal. All my trials and errors.. I could write all day, and I am sure it is a simple solution for someone that know how cake libs work.
$hours = $this->UserHours->find('all', [
'conditions' => [
'UserHours.user_id' => $this->Auth->user('id'),
'month(UserHours.date)' => $this->request->data('date.month')
],
'order' => ['UserHours.date ASC'],
'group' => ['UserHours.date']
]);
And the foreach loop:
foreach ($projecthours as $hour):
debug($hour);
?>
<tr>
<td> <?php echo $hour->date;?> </td>
<td> <?php echo $hour->start; ?> </td>
<td> <?php echo $hour->end; ?> </td>
</tr>
My problem is that I have no idea how to loop trough the records correctly when grouped from controller. I cant find them when using the "group" condition in controller. I only get the first record of each date when using "group".
:) I guess they are somewhere inside there, but I cant figure this one out. I am quite new to cake 3.4..
After you get the grouped dates, you get all dates matching each grouped date.
// get grouped dates
$dates = $this->UserHours->find('all', [
'conditions' => [
'UserHours.user_id' => $this->Auth->user('id'),
'month(UserHours.date)' => $this->request->data('date.month')
],
'order' => ['UserHours.date ASC'],
'group' => ['UserHours.date']
]);
$hours = [];
// find all dates for each grouped date
foreach ($dates as $date) {
$hours[] = $this->UserHours->find('all', [
'conditions' => [
'UserHours.user_id' => $this->Auth->user('id'),
'month(UserHours.date)' => $this->request->data('date.month')
],
'order' => ['UserHours.date ASC']
])
->where(['UserHours.date' => $date->date]);
}
foreach ($hours as $values) {
foreach ($values as $hour) {
dd($hour->date);
}
}
That's the expected result, as that is how SQL grouping works, you get one value per group, there simply will be no further values in the results.
If you just want to output things in a grouped manner, then that's something different, for that you have to select all data, and then you could simply group the results on PHP level, for example using the collection/resultset method groupBy():
$query = $this->UserHours->find('all', [
'conditions' => [
'UserHours.user_id' => $this->Auth->user('id'),
'month(UserHours.date)' => $this->request->data('date.month')
],
'order' => ['UserHours.date ASC']
]);
// callback usage required as `date` is most likely an object
$groupedByDate = $query->all()->groupBy(function ($row) {
return $row['date']->format('Y-m-d');
});
// if it weren't an object, then passing the fields name would already do it
// $groupedByDate = $query->all()->groupBy('date');
foreach ($groupedByDate as $date => $group)
{
// $date = the value of UserHours.date shared by all entities in the group
// $group = an array of UserHour entities that share the same UserHours.date value
foreach ($group as $hour)
{
// ...
}
}
See also
Cookbook > Database Access & ORM > Query Builder > Queries Are Collection Objects
Cookbook > Collections > Collection::groupBy()
Looking to limit the returned fields of a WP Query to help with speeding up the response from the server and reducing the amount of data retrieved. For the query I'm using, it only needs up to 3 fields of data, the rest is brought in through ACF get_field_object in the loop. Other functions I'm using such as get_posts or get_terms have field options but are limited to a small number of things, such as 'slug' only or 'id => slug'.
I'm used to developing in CakePHP, which has the option to specify each and every field to return, but the project calls for wordpress for other functionality and so I'm quite limited.
TL;DR need to speed up getting posts from Wordpress
I used fields parameter in the query and run get posts on this query.
For example: In my case, I just needed to get the Post ids for multiple categories, so I created a query like this:
$the_query = new WP_Query( array(
'ignore_sticky_posts' => 1,
'posts_per_page' => -1,
'cat' => '2,6,7' ,
'fields' => 'ids',
'post_type' => 'post',
'post_status' => 'publish',
)
);
Run the get_posts on this query:
$posts = $the_query->get_posts();
$posts will get only the IDs of particular categories posts.
Or it can also be done with the standard and popular way and i.e., by running the loop of have_posts:
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id_array[] = get_the_ID();
}
}
These are the two ways to help with speeding up the response from the server and reducing the amount of data retrieved
WP_Query will return objects...so it's pretty fast. However, if you really want to limit what's returned, you can do so with the Return Fields Parameter of WP_Query.
I don't know how much it will help but below is how I'm getting a flattened array from a CPT. It's not the fastest but it could be worse. I'm using ACF to get a Custom Field but you could just get back the slug or you could get back multiple fields instead:
// Query Jobs Args
$query_args = array(
'post_type' => 'job',
'posts_per_page' => -1,
'fields' => 'ids'
);
// Get Jobs Query
$query = new WP_Query($query_args);
// Loop Persistent Vars
$job_ids = array();
// Loop Over Jobs
foreach($query->posts as $post_id) {
$job_ids[] = get_field('job_id', $post_id);
}
// Do stuff with flattened array of job ids
This is what I've done to limit the fields from WP_Query, especially, when I want to json_encode them. The $return variable contains my array of posts with only the fields listed in the $fields array.
$query = new WP_Query( array( 'post_type' => 'my_custom_type' ) );
$return = array();
$fields = array('post_title', 'ID'); //list of fields I want in $return
$posts = $query->get_posts();
foreach($posts as $post) {
$newPost = array();
foreach($fields as $field) {
$newPost[$field] = $post->$field;
}
$return[] = $newPost;
}
Interestingly enough, you can do this with the WP Rest API using the _fields parameter
https://yoursite.com/wp-json/wp/v2/posts?_fields=author,id,excerpt,title,link
More info on the API here: https://developer.wordpress.org/rest-api/
I'm trying to update some data and I'm having the next message:
A four digit year could not be found Data missing
In this form, I have some data that I want to update in my 'Actividad', so I have created an array with every field I need to update.
But, one of the form fields, I don't want to put it in the same array, because I need it to update the data in a pivot table ('actividad_material').
By the moment, I'm not able to update any of them... :(
Here is my code:
public function update($id)
{
$input = array(
'titulo' => Input::get('titulo'),
'actividad' => Input::get('actividad'),
'datos' => Input::get('datos'),
'solucion' => Input::get('solucion'),
'minutos' => Input::get('minutos'),
'tipo_id' => Input::get('tipo_id'),
'asignatura_id' => Input::get('asignatura_id'),
'bloque_id' => Input::get('bloque_id'),
'contenido_id' => Input::get('contenido_id'),
'objetivo_id' => Input::get('objetivo_id'),
'nivel_id' => Input::get('nivel_id'),
'etapa_id' => Input::get('etapa_id'),
'm_desc' => Input::get('m_desc'),
'slug' => Str::slug(Input::get('titulo')),
'user_id' => Sentry::getUser()->id,
'_method'
);
$v = Validator::make($input, Actividad::$rules);
if($v->passes())
{
// Trying to update my pivot table...
$actividad = Actividad::find($id);
$material_id = array(
'material_id' => Input::get('material_id'));
$actividad->materials->sync($material_id);
Actividad::find($id)->update($input);
return Redirect::route('actividads.index');
}
return Redirect::back()->withErrors($v);
}
Any idea why I'm getting this error? Maybe the timestamps?
What am I doing wrong when updating?
Thank you very much in advance!!