fridge_bites/apps/Recipes/Models/RecipeUserMenu.php

94 lines
2.6 KiB
PHP

<?php
namespace Lycoreco\Apps\Recipes\Models;
use Lycoreco\Apps\Users\Models\UserModel;
use Lycoreco\Includes\Model\BaseModel;
class RecipeUserMenu extends BaseModel
{
public $field_dayofweek;
public $field_recipe_id;
public $field_user_id;
public $field_created_at;
static protected $table_name = 'recipe_usermenu';
static protected $table_fields = [
'id' => 'int',
'dayofweek' => 'string',
'recipe_id' => 'int',
'user_id' => 'int',
'created_at' => 'DateTime'
];
public static function init_table()
{
$result = db_query('CREATE TABLE ' . static::$table_name . ' (
id INT AUTO_INCREMENT PRIMARY KEY,
dayofweek VARCHAR(150) NOT NULL,
recipe_id INT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (recipe_id) REFERENCES recipes(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);');
return $result;
}
public function valid()
{
require_once INCLUDES_PATH . '/Const/recipes.php';
if (!in_array($this->field_dayofweek, DAYS_OF_WEEK))
return ['Day of Week is not valid'];
$recipe = RecipeModel::get(array(
[
'name' => 'obj.id',
'type' => '=',
'value' => $this->field_recipe_id
]
));
if (!$recipe)
return ['Recipe does not exist'];
return true;
}
public static function get_prefetch_recipes(UserModel $user, string $week) {
$usermenus = RecipeUserMenu::filter(array(
[
'name' => 'obj.user_id',
'type' => '=',
'value' => $user->get_id(),
],
[
'name' => 'obj.dayofweek',
'type' => '=',
'value' => $week
]
), count: 100);
if(empty($usermenus))
return [];
$usermenu_ids = array_map(function($usermenu) {
return $usermenu->field_recipe_id;
}, $usermenus);
$recipes = RecipeModel::filter(array(
[
'name' => 'obj.id',
'type' => 'IN',
'value' => $usermenu_ids
]
));
$prefetch_recipes_ings = prefetch_related($recipes, 'Recipes:IngredientInRecipeModel', 'recipe_id');
return $prefetch_recipes_ings;
}
}