Unable to find table class for current entity error in cakephp 3 - cakephp-3.0

In my below code when I am getting complete zero result pr zero rows that time I am getting this error:
Unable to find table class for current entity error
And if any row is coming in the pagination that time everything is working fine.
Where I am doing wrong?
$prProductFind=$this->PurchaseRequisitionProducts
->find()
->where([$condn,$conditions])
->matching('PurchaseOrderProducts', function(\Cake\ORM\Query $q) {
return $q->where(['PurchaseOrderProducts.id IS NOT NULL']);
})
->matching('PurchaseOrderProducts.PurchaseOrder', function(\Cake\ORM\Query $q) {
return $q->where(['PurchaseOrder.id IS NOT NULL','PurchaseOrder.is_approve'=>"Y",'PurchaseOrder.po_type'=>1,'PurchaseOrder.status'=>1]);
})
->group(['PurchaseRequisitionProducts.id'])
->order(["PurchaseRequisitionProducts.id"=>"desc"]);
$pr_product = $this->paginate($prProductFind);

Related

How to fetch all row data from database using Laravel 8

I have records in a database with three different records in a particular column. I am trying to fetch all the records using Laravel but I am not getting it right after trying with multiple methods and each method is fetching only one record. I would be glad if I get assistance and to also learn from what I am not getting right. Thank you in advance.
Below is the code:
public function setBill()
{
//With the below, I am getting only one record
$FetchData = Students::all();
foreach ($FetchData as $Data) {
dd($Data->class);
}
//With this too, I am getting only one record
$FetchData = Students::get();
foreach ($FetchData as $Data) {
dd($Data->class);
}
//With this as well, I am getting only one record
$FetchData = DB::select('select * from students');
foreach ($FetchData as $Data) {
dd($Data->class);
}
}
What's happening is that dd() is stoping your script execution (dump and die).
If you want to see all fetched records you should do
$FetchData = Students::all();
dd($FetchData);
Otherwise, if you want to dump one record by one
$FetchData = Students::get();
foreach ($FetchData as $Data) {
dump($Data->class);
}

Sequelize search from a column that contains JSON array in mysql table

In my mysql table ,i have a column of JSON type
const monthlyProgress = sequelize.define("monthlyprogress", {
.
.
.
duration: {
type: Sequelize.JSON
}
});
return monthlyProgress;
in this "duration" column i have a JSON array of objects
[{"time":"nov-2020"},{"time":"dec-2020"}]
Now i need a sequelize findall to fetch the rows where the condition will e
time = "nov-2020" of that "duration" column
i have tried i many ways but failed everyime. Below i am showing one of the ways that i found on stackoverflow. But its also a failed attepmt
Its giving me output of those rows who doesnt have time="nov-2020"
await monthlyProgress.findAll({
where: {
duration: [
fn('JSON_CONTAINS', col('duration'), cast('{"time": "nov-2020"}', 'CHAR CHARACTER SET utf8'))
]
}
})
It's another attempt thats is showing this error message UnhandledPromiseRejectionWarning: ReferenceError: JSON_CONTAINS is not defined
await monthlyProgress.findAll({
where: {
[Op.and]: db.Sequelize.literal(JSON_CONTAINS(`duration`, '{\"time\": nov-2020}')),
}
})

How do I return a union as an Active Record object?

I have these union in my controller :
$expression = new Expression('"News"');
$featuredNews2= news::find()
->alias('ne')
->select(['ne.title', 'ne.content','ne.featuredOrder', 'category'=>$expression])
->innerJoinWith('featuredOrder1');
$expression2 = new Expression('"Event"');
$featuredEvents2 = event::find()
->select(['ev.title', 'ev.content','ev.featuredOrder','category'=>$expression2])
->from('event ev')
->innerJoinWith('featuredOrder2');
$union = $featuredNews2->union($featuredEvents2);
The relation in model :
news model
public function getFeaturedOrder1()
{
return $this->hasOne(Featured::className(), ['featuredOrder' => 'featuredOrder']);
}
event model
public function getFeaturedOrder2()
{
return $this->hasOne(Featured::className(), ['featuredOrder' => 'featuredOrder']);
}
I need to return the query as an Active Query because I need to access my model's method e.g : $model->featuredOrder1->preview in my view.
The following works but it returns an array, as the result I can't access my model's method :
$unionQuery = (new \yii\db\Query)->select('*')
->from($union)
->orderBy('featuredOrder')->all(\Yii::$app->db2);
I have two questions :
How to return the equivalent $unionQuery above but as an active query object? I have googled and search on SO but what I found is how to return it as array.
This is out of curiosity, I wonder why I should provide my db connection as argument in my $unionQuery all() method above. If I didn't use an argument that point to db2, it will look for table name inside my db database instead ( db is my parent database, this db2 is my module's database/the correct one). This only happen with a union. My news and event model already have this in getdb() function:
return Yii::$app->get('db2');
update
I've tried this too :
$unionProvider = (new ActiveQuery(Featured::className()))->select('*')
->from(['union' => $featuredEvents2->union($featuredNews2)])
->orderBy('featuredOrder');
With this relation in featured model:
public function getNews()
{
return $this->hasOne(News::className(), ['featuredOrder' => 'featuredOrder']);
}
public function getEvents()
{
return $this->hasOne(Event::className(), ['featuredOrder' => 'featuredOrder']);
}
and in the view, I tried this :
foreach($unionProvider as $key=>$model){
echo $model->news->title;
}
but get this error : Trying to get property of non-object
Update 2
I forgot to add ->all() in my $unionProvider, but after that I got this error instead : PHP Fatal Error – yii\base\ErrorException
Allowed memory size of 134217728 bytes exhausted (tried to allocate 12288 bytes)
Might be something wrong with my query? Can't figure it out
You can try using pure SQL. Plus you can test to see if it is returning the correct results and then add it in the statement below.
$customers = Customer::findBySql('SELECT * FROM customer')->all();
Learn more in yii docs

Getting Error When I Start multiple select query inside loop TimeoutError: ResourceRequest timed out

I'm using nodeJs Express Framework.
I'm using mysql database with sequelizejs library and using querying for retrieve data.
I am getting timeout error when I fired select query for almost 50,00,000 records.
I have done the server timeout but not worked.
I have done the pooling method in sequlizeJs But not worked.
function fetchNamesData(req, name) {
return new Promise((resolve, reject) => {
const names = req.app.locals.models.names_data;
names.findAll({
where: {
name: name
},
order: [['date', 'DESC']],
limit: 50
})
.then(function (dbRes) {
console.log(dbRes.length);
resolve(dbRes);
})
.catch(function (dbErr) {
console.log(dbErr);
return reject(dbErr);
});
});
}
allNames.forEach(element => {
//console.log(element.dataValues.name);
fetchNamesData(req, element.dataValues.name).then((dbRes) => {
//here I will have all the records
}).catch((dbErr) => { console.log(dbErr) });
var allNames = {having almost 7000 names}
now I iterate this obj and each names having 50 record in database
I want to get that all record like 50*7000 = 3,50,000.
What happens in your case is :
Looping through 7000 names and at same time hitting 7000 queries in mySql , and mysql will create queue for executing 7000 queries at same time cause load on machine. Either you can update your configuration to handle such load OR
Solution to this : Try to put some timeout b/w each queries , this way you will be able to fetch more records ,
allNames.forEach(element => {
setTimeout(() => { // <----------- HERE -------------
fetchNamesData(req, element.dataValues.name).then((dbRes) => {
//here I will have all the records
}).catch((dbErr) => {
console.log(dbErr)
});
},500); // <----------- HERE -------------
});
I have found the solution like
- Remove the unwanted console.log() and
- Also your hardware configuration depend upon it for timeout error.
- When query is firing do not start or run any other work it will lead to time out error[when there are multiple crud operation is going on].
- Also give index to table field when particular field is going to use in where clause.

Can't catch my mysql errors

I am using codeigniter for my server side in php.
I set my email field UNIQUE on my Users table.
The problem is that whatever I tried I can't catch the error mysql generated when trying to insert a duplicate email.
What i tried inside my model:
function insert($arr) {
$query= $this->CI->db->insert('user', $arr);
if($query){
return $this->CI->db->insert_id();
} else {
$msg = $this->CI-db->_error_message();
return $msg;
}
}
The issues goes that everything is fine until I get a duplicate and I actually get NOTHING inside the $msg. I know debug is on from the database config file.
If your database config 'db_debug' => TRUE, your code will exit with showing the error message and you will not able to reach this line $msg = $this->CI-db->_error_message();.
So to catch the error message you need to set the.
db_debug' => FALSE
At CI-2 your above code will work.See more at this question
But At CI-3 those function is not available and it will produce php undefined method error. CI-3 has a method display_error. You can check it.
My solution: If you want the errors you can get it using this line
$msg = $this->db->conn_id->error_list;
This will give you the error lists as array.But remember you need to set db_debug' => FALSE