Laravel SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in - laravel

I'm working on a Laravel blog and and the moment, I want to change the status of the Post status based on a certain condition using an event. In my migration, I have a post_status enum table with the statuses I want to use and I have wired up the event and the listener, also have set up the dispatchesEvents using retrieved, so I'm not really posting anything.
I want to change posts that currently have a status of Complete AND are older than 90 days to the Archived status. For this, I am using the code below. The status actually updates based on the first condition but I'm not sure the second condition is being taken into account (or is it properly defined), my hunch is that the issue is with the last line. This is the code in the listener:
public function handle(PostStatusUpdaterEvent $event)
{
$old_date = Carbon::now()->subDays(90);
Post::where(['post_status' => 3]) // 3 = Complete status
->where(['end_date', '<', $old_date])
->update(['post_status' => 4]); // 4 = Archived status
}
And the error:
lluminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: update
`posts` set `post_status` = 4, `posts`.`updated_at` = 2020-02-24 13:13:15 where
(`post_status` = 3) and (`0` = end_date and `1` = < and `2` = 2019-11-26 13:13:15))
I have the post_status field in my protected fillable array, also have the table itself protected. Also tried setting the post_status field in the protected appends array, also tried setting the table id as hidden, none of which worked. Finally, I have model and Carbon namespace imported in the listener (as in use...)

You would use array in where only if you want to run multiple checks within the same where
WHERE (`post_status` = 3 AND `end_date` = '2019-11-26 13:13:15')
Proper code for that would be
Post::where([
['post_status', 3], // 3 = Complete status
['end_date', '<', $old_date],
])
->update(['post_status' => 4]); // 4 = Archived status
To produce WHERE `post_status` = 3 AND `end_date` < '2019-11-26 13:13:15'
You would go with (without array notion)
Post::where('post_status', 3) // 3 = Complete status
->where('end_date', '<', $old_date)
->update(['post_status' => 4]); // 4 = Archived status
See Where Clauses for more info.

Change the second where to this:
where('end_date', '<', $old_date)

Related

Codeigniter updating data with OR condition in ID

Hello I am a beginner in using Codeigniter. What I want is to update a data in Codeigniter with an OR condition to the ID.
Here is my MySQL query that I want to make happen:
Update message_received SET is_read = 1 WHERE msg_id = 3 OR parent_id = 3
I tried something like this:
$this->query->update_array('message_received', array('msg_id' => $_POST['read_my_message'],'parent_id' => $_POST['read_my_message']) , array('is_read'=>1));
You can use or_where to apply OR condition in CodeIgniter, I've written a possible solution for your question(Reference).
See if it helps you.
$msg = $this->input->post('read_my_message'); // get the post data
$this->db->set('is_read', 1); // set the value of column
$this->db->where('msg_id', $msg); // first condition
$this->db->or_where('parent_id', $msg); // second contion
$this->db->update('message_received'); // table name
// Produces:
/* UPDATE `message_received` SET `is_read` = 1 WHERE `msg_id` = '$msg' OR `parent_id` = '$msg' */
You can apply OR. The references https://www.codeigniter.com/userguide3/database/query_builder.html

In Laravel, can we sum related models attribute using withCount method?

I have 3 models related like so :
Prize -> TimeSlot -> Winner, with their corresponding relationship methods $prize->hasMany(TimeSlot) and $prize->hasManyThrough(Winner, TimeSlot).
I am trying to count in one eloquent query the number of winners and the number of time slots.
Here is the query :
$prizes = $prizes->withCount(['winners', 'timeSlots' => function ($query) {
$query->sum('min'); // min is an attribute on TimeSlot
}])->get();
This gives me the number of winners with a winners_count attribute on each prize. I thought it would give me the 'sum number' of time slots for each prize but the query breaks on that part with an error like :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'prizes.id' in 'where clause'
(SQL: select sum(`min`) as aggregate from `time_slots` where `time_slots`.`prize_id` = `prizes`.`id`)
The documentation of withCount method only show how to constraint the query (with a where clause for example) but not with an aggregate like sum.
P.S: I already know how to do this with something like :
$prizes = $prizes->with('timeSlots')->withCount('winners')->get();
$numOfWinners = $prizes->sum('winners_count');
$numOfAvailablePrizes = $prizes->sum(function ($prize) {
return $prize->timeSlots()->sum('min');
});
But i thought the version with one query would save me some useless loops...
Thanks for answers !
Try this
$query->withCount(['timeSlots AS timeslots_sum' => function ($query) {
$query->select(DB::raw('SUM(min) as timeslots_sum'));
}]);
It will returns
"timeslots_sum" => "123" // total

error laravel variable in a query to check date

i try since 2 days to create a query to select the right categorieAgerange depend on the $variable = dt_naissance
first i have two tables : licencie(id , ... , catg_licence_id)
catg_licence(id , lb_name , nb_age_min , nb_age_max)
here my function store :
public function store(Request $request)
{
$licencie = new Licencie;
$licencie->club_id = $request->input('club_id');
$licencie->structure_id = $request->input('structure_id');
$licencie->dt_naissance = $request->input('dt_naissance');
$licencie->pays_naissance_id = $request->pays_naissance_id;
//here i check the age of the licence
$dt_naissance = Carbon::parse($request->dt_naissance)->diff(Carbon::now())->format('%y');
dd($dt_naissance) -> i get the good age like "2" for two years for people who select 2014 for exemple
then i would like to make a between query to select the propor catg_licence_id to my licence and inject to my database
i tried this :
$catg_licence_id = CatgLicence::whereBetween($dt_naissance , ['nb_age_min' , 'nb_age_max'])->firstOrFail()->id;
but i get an error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column '22' in 'where clause' (SQL: select id from catg_licence where (22 between nb_age_min and nb_age_max))
someone have an idea how i can resolve the problem ? thanks in advance :)
whereBetween takes the column as the first parameter.
->whereBetween('age', [1, 100])->get();
But in your case you might want to try
CatgLicence::where('nb_age_min', '<', $dt_naissance)
->where('nb_age_max', '>', $dt_naissance)
->first();
Try that one and see how it goes.
Bonne chance!

Magento. Unknown column 'sales_flat_order_item.order_id'

all. I'm trying to get all order items from database, where order status is not "canceled". Here is a piece of code:
$items = Mage::getModel('sales/order_item')->getCollection();
$rents->getSelect()->join( array('sales_order'=>Mage::getSingleton('core/resource')->getTableName('sales/order')), Mage::getSingleton('core/resource')->getTableName('sales/order_item') . '.order_id = sales_order.entity_id', array('sales_order.state'));
$rents->addFilter('product_id', $productId);
$rents->addFilter('state', array('neq' => 'canceled'));
Dut, when i'm trying to run this code, i get an error: "Column not found: 1054 Unknown column 'sales_flat_order_item.order_id' in 'on clause'"
Try below code to desire result, I have tried with one of the ordered product.
$items = Mage::getModel('sales/order_item')->getCollection();
$items->getSelect()->join( array('sales_order'=>Mage::getSingleton('core/resource')->getTableName('sales/order')), 'main_table.order_id = sales_order.entity_id', array('sales_order.state'));
$items->getSelect()->where('product_id=?', $productId);
$items->getSelect()->where('state!=?','canceled');
echo $items->getSelect();// will print sql query
print_r($items->getData()); // will print order into array format
Hope it will help!

code igniter updating a row with multiple values to a column

I am getting a array to my model. Say array has an value 1 and 2.
Now I need to update this to a single column 1,2 so that column will look like this
Column
1,2
foreach($x as $y){
$this->db->where('column',4);
$this->db->set('id',$data);
$this->db->update('table');
}
But this is only update 2, it is omitting 1. Where am i going wrong ?
If you want to save multiple values in a column put them in
an array and serialize them. Than save it in column.
Make the column type text.
$array['name'] = 'test';
$array['otherinfo'] = 'otherinfo';
$data = serialize($array);
foreach($x as $y)
{
$this->db->where('column',4);
$this->db->set('id',$data);
$this->db->update('table');
}
When you select you can unserialize the array using unserialize();
Use implode
For example:
$data = [1,2]
$comma_data = implode(",", $data)
Then update column with $comma_data
I was having wrong data type, I figured it out.

Resources