Example #1
0
 /**
  * Returns the foods that are linked to this scheme part.
  *
  * @return \TableRecords\Food[]
  */
 public function getFoods() : array
 {
     if (!$this->foods) {
         $table = new \Tables\SchemePartFoods();
         $linking_records = $table->by('scheme_part_id', $this->id)->get();
         if (!$linking_records) {
             return [];
         }
         $food_ids = [];
         $amounts = [];
         // Amounts in grams per food for this scheme part.
         foreach ($linking_records as $record) {
             $food_ids[] = (int) $record->food_id;
             $amounts[$record->food_id] = (int) $record->amount;
             // Amount of food in grams.
         }
         $food_ids = array_unique(array_filter($food_ids));
         if (!$food_ids) {
             return [];
         }
         $foods_table = new \Tables\Foods();
         $foods = $foods_table->where('id IN (' . implode(',', $food_ids) . ')')->get();
         // Add amount in grams to foods.
         foreach ($foods as $i => $food) {
             $foods[$i]->amount = $amounts[$food->id] ?? 0;
         }
         $this->foods = $foods;
     }
     return $this->foods;
 }
Example #2
0
$scheme_part_id = !empty($_POST['id']) ? (int) $_POST['id'] : null;
$update = !!$scheme_part_id;
$table = new \Tables\SchemeParts();
if ($update) {
    // May the current user edit this scheme part?
    $scheme_part = $table->by('user_id', getUser()->id)->get($scheme_part_id);
    if (!$scheme_part) {
        return $Javascript->setError(__('You are not authorized to edit this scheme part.'))->output();
    }
}
if ($update) {
    $table->update($_POST, $scheme_part_id);
} else {
    $data = $_POST;
    $data['user_id'] = getUser()->id;
    $scheme_part_id = $table->create($data);
}
# Update scheme part food table.
$table = new \Tables\SchemePartFoods();
if ($update) {
    // Delete existing scheme part foods.
    $table->by('scheme_part_id', $scheme_part_id)->delete();
}
// Add new scheme part foods.
$amounts = $_POST['amounts'] ?? array();
foreach ($amounts as $food_id => $amount_in_g) {
    $table->create(['scheme_part_id' => $scheme_part_id, 'food_id' => $food_id, 'amount' => (int) $amount_in_g]);
}
$Ase->happen('cache_update', ['scheme_parts', ['scheme_part_id' => $scheme_part_id]]);
$Javascript->setOutput('id', $scheme_part_id);
$Javascript->setSuccessMessage(__('Scheme part saved.'))->output();