Unable to change Variable Value in CI4 - php

I am unable to change the model value, whenever I try echo the model name (After changing using if condition) the correct modelname value is displayed but if I try to call it using declared modelname value (ignores the changed value) it uses the declared model name from 'line 8 ' i.e. protected $modelName = '';
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\IncomingRequest;
use DateTime;
class igmc_pat_dat extends ResourceController
{
protected $modelName = '';
protected $format ='json';
protected $requestedModule;
public function index(){
$request = service('request');
$fromDate = $request->header('fromDate')->getValue();
$toDate = $request->header('toDate')->getValue();
$requestedModule = $request->header('module-code')->getValue();
$temtodate = DateTime::createFromFormat('d/m/Y h:i:s', $toDate);
$formatedtoDate=$temtodate->format("Y-m-d h:i:s");
$ddd= DateTime::createFromFormat('d/m/Y h:i:s', $fromDate);
$formatedDate = $ddd->format("Y-m-d h:i:s");
// $pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->where('datetime_of_txn <', $formatedtoDate)->findAll();
// return $this->respond($pat_rec);
if($requestedModule){
if($requestedModule==1){
$this->modelName = 'App\Models\igmc_pat_1_model';
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate))->findAll();
return $this->respond($pat_rec);
}
else if($requestedModule==2){
$this->modelName = 'App\Models\igmc_pat_2_model';
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->findAll();
return $this->respond($pat_rec);
}
else{
echo " Data Requested";
}
}
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->where('datetime_of_txn <', $formatedtoDate)->findAll();
return $this->respond($pat_rec);
}
?>

Your just changing the model name not the actual model. Use the model classmember.
From BaseResource.php:
/**
* #var string|null The model that holding this resource's data
*/
protected $modelName;
/**
* #var object|null The model that holding this resource's data
*/
protected $model;
Use it like this:
use App\Models\igmc_pat_1_model;
use App\Models\igmc_pat_2_model;
...
if ($requestedModule) {
if ($requestedModule == 1) {
$this->model = new igmc_pat_1_model(); // Change here
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->findAll();
return $this->respond($pat_rec);
} else if ($requestedModule == 2) {
$this->model = new igmc_pat_2_model(); // Change here
$pat_rec = $this->model->where('datetime_of_txn >', $formatedDate)->findAll();
return $this->respond($pat_rec);
} else {
echo " Data Requested";
}
}
Furthermore your code is missing a } (line 57) and has a ) (line 40) to much.

Related

Laravel Submodel Of an Model

In my Laravel application, I need submodels of the base ORM model, for specific types of item in my DB which is specified in 'type' column in database.
In my base model, I use this override for function newFromBuilder
// OVERRIDES
public function newFromBuilder($attributes = [], $connection = null)
{
$class = "\\App\\Models\\" . ucfirst($attributes->type);
if (class_exists($class)) {
$model = new $class();
} else {
$model = $this->newInstance([], true);
}
$model->setRawAttributes((array)$attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
but for some reason when i call save or update function in submodel nothing happen :( Each submodel should ingered save function of fase model s that right ? Could anybody help me to fix issue with save function ?
Base model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use App\Models\Devices;
use App\Models\Records;
use App\Models\Rooms;
use App\Helpers\SettingManager;
use App\Types\GraphPeriod;
use App\Types\PropertyType;
class Properties extends Model
{
protected $fillable = [];
protected $table = 'sh_properties';
protected $primaryKey = 'id';
public $period = GraphPeriod::DAY;
//OVERIDES
public function newFromBuilder($attributes = [], $connection = null)
{
$class = "\\App\\Models\\" . ucfirst($attributes->type);
if (class_exists($class)) {
$model = new $class();
} else {
$model = $this->newInstance([], true);
}
$model->setRawAttributes((array)$attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
//NEW RELATIONS
public function records()
{
return $this->hasMany(Records::class, 'property_id');
}
public function latestRecord()
{
return $this->hasOne(Records::class, 'property_id')->latestOfMany();
}
public function device()
{
return $this->belongsTo(Devices::class);
}
public function room()
{
return $this->belongsTo(Rooms::class);
}
public function settings()
{
if ($settings = SettingManager::getGroup('property-' . $this->id)) {
return $settings;
}
return false;
}
//FUNCTIONS
public function getLatestRecordNotNull()
{
return Records::where("property_id", $this->id)->where("value", "!=", null)->where("value", "!=", 0)->first();
}
//Virtual Values
use HasFactory;
//Add Function for mutator for vaue (vith units) and rav value
public function values()
{
$dateFrom = Carbon::now()->subDays(1);
switch ($this->period) {
case GraphPeriod::WEEK:
$dateFrom = Carbon::now()->subWeek(1);
break;
case GraphPeriod::MONTH:
$dateFrom = Carbon::now()->subMonth(1);
break;
case GraphPeriod::YEAR:
$dateFrom = Carbon::now()->subYear(1);
break;
}
return $this->hasMany(Records::class, 'property_id')->whereDate('created_at', '>', $dateFrom)->orderBy('created_at', 'DESC');
}
public function getAgregatedValuesAttribute($period = GraphPeriod::DAY)
{
$dateFrom = Carbon::now()->subDays(1);
$periodFormat = "%Y-%m-%d %hh";
switch ($this->period) {
case GraphPeriod::WEEK:
$dateFrom = Carbon::now()->subWeek(1);
$periodFormat = "%Y-%m-%d";
break;
case GraphPeriod::MONTH:
$dateFrom = Carbon::now()->subMonth(1);
$periodFormat = "%Y-%m-%d";
break;
case GraphPeriod::YEAR:
$dateFrom = Carbon::now()->subYear(1);
$periodFormat = "%Y-%m";
break;
}
$agregatedData = Records::select(['value', 'done', 'created_at'])
->selectRaw("DATE_FORMAT(created_at, ?) as period", [$periodFormat])
->selectRaw("ROUND(MIN(value), 1) AS min")
->selectRaw("ROUND(MAX(value), 1) AS max")
->selectRaw("ROUND(AVG(value), 1) AS value")
->where('property_id', $this->id)
->orderBy('created_at', 'DESC')
->groupBy('period');
$agregatedData->where('created_at', '>=', $dateFrom);
return $agregatedData->get();
}
public function last_value()
{
return $this->hasOne(Records::class, 'property_id', 'id')->latest();
}
//Virtual Values
//Virtual Values
/**
* Minimum value that property had in past.
*
* #return int
*/
public function getMaxValueAttribute()
{
if ($this->records) {
return $this->records->max("value");
}
return false;
}
/**
* Maximum value that property had in past.
*
* #return int
*/
public function getMinValueAttribute()
{
if ($this->records) {
return $this->records->min("value");
}
return false;
}
/**
* step value used to increment each value usually used for range type or thermostats, graphs also.
*
* #return int
*/
public function getStepValueAttribute()
{
if ($step = SettingManager::get('step', 'property-' . $this->id)) {
return ($step->value < 1 ? $step->value : 1);
}
return false;
}
/**
* max set value for prop
*
* #return int
*/
public function getMaxValueSettingAttribute()
{
if ($step = SettingManager::get('max', 'property-' . $this->id)) {
return ($step->value > 1 ? $step->value : 1);
}
return false;
}
/**
* min set value for prop
*
* #return int
*/
public function getMinValueSettingAttribute()
{
if ($step = SettingManager::get('min', 'property-' . $this->id)) {
return ($step->value > 1 ? $step->value : 1);
}
return false;
}
public function setValue($value)
{
$record = new Records;
$record->value = $value;
$record->property_id = $this->id;
$record->save();
return true;
}
}
Submodel
namespace App\Models;
use App\Models\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Humi extends Properties
{
protected $historyDefault = 90;
protected $unitsDefault = "%";
protected $iconDefault = "";
public function save(array $options = [])
{
// before save code
$result = parent::save($options); // returns boolean
// after save code
return $result; // do not ignore it eloquent calculates this value and returns this, not just to ignore
}
}
Thank you in advance for any suggestions or help :)
When a new instance is created with the $this->newInstance() function, the $model->exists property is set to true. I think you should do the same in your if statement as well. Otherwise it will try to create a new record in the database.
It might be a good idea to copy the rest of the function as well to avoid any other problems it may cause.
if (class_exists($class)) {
$model = new $class();
// Important
$model->exists = true;
$model->setTable($this->getTable());
$model->mergeCasts($this->casts);
} else {
$model = $this->newInstance([], true);
}

No query results for model [App\User] NULL 387 /laravel/framework/src/Illuminate/Database/Eloquent/Builder.php

I know a similar question has been asked but the reasons for those error does not imply in my case because I am not fetching results anywhere in code.
I am not using the 'find' or 'findOrFail' method anywhere in code.
I am getting this error:
No query results for model [App\User] NULL 387 /laravel/framework/src/Illuminate/Database/Eloquent/Builder.php
My Excel import code:
<?php
namespace App\Imports;
use Auth;
use App\User;
use App\EmployeePerformance;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class HierarchyImport implements ToCollection, WithHeadingRow {
public function collection(Collection $rows) {
foreach ($rows as $row) {
$user = $this->createUserNew($row, $row['role'], $row['parent_id']);
}
}
/**
* Transform a date value into a Carbon object.
*
* #return \Carbon\Carbon|null
*/
public function transformDate($value, $format = 'Y-m-d'){
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function createUserNew($row, $role, $parent_id){
$emp_id = $row['employee_id'];
$name = $row['employee_name'];
$email = $row['email'];
$user = new User;
$user->company_id = 1;
$user->employee_id = $emp_id;
$user->parent_id = $parent_id;
$user->title = $row['title'];
$user->region_number = 2;
$user->name = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $name));
$user->email = $email;
$user->email_verified_at = null;
$user->gender = ($role == 'employee') ? $row['gender'] : null;
$user->hire_date = ($role == 'employee') ? $this->transformDate($row['hire_date']) : null;
$user->date_of_birth = null;
$user->age = ($role == 'employee') ? $row['dob'] : null;
$user->password = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'; // password
$user->employee_status = 0;
$user->save();
if($user)
//$user = $user->assignRole($role);
return $user;
}
}
In my controller:
$import = new HierarchyImport;
$importExcel = Excel::import($import, $request->file('file'));
PS:
I tried User::create($user); but the same result, and the create method is returning the No query results for the model.
So I found out that some of the fields in the excel file are null, and when I was trying to insert them, it was giving the strange error No query results for model.
This has been fixed by handling the null values before inserting.

PHP static property with extending class overwritten

Please, could you help me a bit with my problem?
I have class called Translateable and then clasess Article and Banner, which extend this class.
Problem occurs, when I do this:
$article = (new Article)->find(15);
$banner = (new Banner)->find(1);
$articleTrans = $article->trans(); // method trans is method from Translateable
When I call $article->trans(); I expect output like this:
App\Models\ArticleTrans
Article
but it return this:
App\Models\ArticleTrans
Banner
First row is ok, but the second one if bad and I don't know, how to solve this problem.
I need to have $instance stored as static property.
Could you give me you help?
class Translateable extends Model {
static $transLang = null;
static $transClass = null;
static $instance = null;
public function __construct(array $attributes = array()) {
static::$transLang = App::getLocale();
parent::$transClass = static::$transClass;
parent::$instance = static::$instance;
parent::__construct($attributes);
}
/**
* get items trans
*
* #param null $lang
* #return mixed
*/
public function trans($lang = null) {
if($lang == null) {
$lang = static::$transLang;
}
echo static::$transClass;
echo class_basename(static::$instance);
die();
}
public static function find($primaryKeyVal, $columns = []) {
$tci = new static::$transClass;
$item = static::withTrans()->where(static::$instance->getTable() . '.' . static::$instance->primaryKey, '=', $primaryKeyVal)->where($tci->getTable() . '.lang', '=', static::$transLang)->first();
return $item;
}
}
class Article extends Translateable {
static $transClass = 'App\Models\ArticleTrans';
public function __construct(array $attributes = array()) {
parent::$transClass = static::$transClass;
parent::$instance = $this;
parent::__construct($attributes);
}
}
class Banner extends Translateable {
static $transClass = 'App\Models\BannerTrans';
public function __construct(array $attributes = array()) {
parent::$transClass = static::$transClass;
parent::$instance = $this;
parent::__construct($attributes);
}
}

PHP object property overritten

I'm solving quite strange problem which I'm facing for the first time.
I have some main Class with property static::$someProperty and I extend with this class other classes, e.g. ClassA and ClassB.
Problem is now, when I load
$classA = ClassA
and set there
static::$someProperty = "ClassA"
and echo this value, it works fine and return "ClassA" but then I also load
$classB = ClassB
and set
static::$someProperty = "ClassB"
and when I
echo static::$someProperty
in $classA now, there is value "ClassB".
Do you know, how to solve this problem? Probably it is connected with static, but I don't now, what to do with this.
class Translateable extends Model{
public static $transLang;
public static $transClassInstance;
public static $instance;
public $transInstance = null;
public function __construct(array $attributes = array()) {
self::$transLang = App::getLocale();
$tcName = static::$instance->transClass;
static::$transClassInstance = new $tcName;
parent::__construct($attributes);
}
/**
* add trans to the item
*
* #return mixed
*/
public static function withTrans($lang = null) {
if($lang == null) {
$lang = static::$transLang;
}
return static::join(static::$transClassInstance->getTable(), function ($join) use ($lang) {
$join->on(static::$instance->getTable() . '.' . static::$instance->primaryKey, '=', static::$transClassInstance->getTable() . '.' . static::$instance->primaryKey)->where(static::$transClassInstance->getTable() . '.lang', '=', $lang);
})->where(static::$transClassInstance->getTable() . '.lang', '=', $lang)
;
}
}
class Nested extends Translateable{
// protected $lft, $lvl, $rgt, $parent_ID;
public static $transClassInstance;
public static $transLang;
public function __construct(array $attributes = array()) {
self::$transLang = App::getLocale();
$tcName = static::$instance->transClass;
static::$transClassInstance = new $tcName;
parent::$instance = $this;
parent::__construct($attributes);
}
/**
*
* get $this item child
*
* #return null
*/
public function getChilds() {
$primaryKeyName = $this->primaryKey;
$parent_id = $this->$primaryKeyName;
// here is echo PageTrans instead of ProductCategoryTrans
echo static::$transClassInstance->getTable().'<br/>';
echo static::$transClassInstance->getTable() . '.lang'.'<br/>';
$query = static::where('parent_ID', '=', $parent_id)->where(static::$transClassInstance->getTable() . '.lang', '=', static::$transLang);
echo $query->toSql();
$this->generateItemsQuery($query);
$query->orderBy('lft', 'ASC');
$categories = $query->get();
return $categories;
}
}
class ProductCategory extends Nested{
public $transClass = 'App\Models\ProductCategoryTrans';
public function __construct(array $attributes = array()) {
static::$instance = $this;
parent::__construct($attributes);
}
}
class Page extends Nested{
public $transClass = 'App\Models\PageTrans';
public function __construct(array $attributes = array()) {
static::$instance = $this;
parent::__construct($attributes);
}
}
Example usage:
// find product category with ID == 1
$productCategory = (new ProductCategory)->find(1); // "ClassA"
// get some page...
$page = (new Page)->find(1); // find page with ID == 1 // "ClassB"
// get childs of loaded category
$categoryChilds = $productCategory->getChilds(); // get this category
Try to use self in classA and classB
self::$someProperty = 'test';

Empty response from Zend_Amf_Server

When I call endpoint from flash all the action is done well but the response is empty. The code is:
class AmfController extends Zend_Controller_Action {
public function indexAction()
{
$server = new Zend_Amf_Server();
$server->setProduction(false);
$server->setClass('Application_Model_Amf');
$response = $server->handle();
echo $response;
}
}
and
class Application_Model_Amf {
/**
*
* #param bytearray $data
* #param string $dateString
* #return int
*/
public function save($data, $dateString)
{
$dateString = str_replace(array('|', ':'), array('_', ''), $dateString);
//file_put_contents("$dateString.jpg", $data);
$r = new stdClass();
$r->error = 0;
return $r;
}
}
I also tried
public function save($data, $dateString)
{
$dateString = str_replace(array('|', ':'), array('_', ''), $dateString);
//file_put_contents("$dateString.jpg", $data);
return true;
}
but it worked neither - still empty response. How can I return response like this stdClass() ? Or only integer value 1 or 0?
The solution is to add die()
public function indexAction()
{
$server = new Zend_Amf_Server();
$server->setProduction(false);
$server->setClass('Application_Model_Amf');
$response = $server->handle();
echo $response;
die();
}

Categories