Reputation: 115
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...)
Upvotes: 0
Views: 721
Reputation: 4124
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.
Upvotes: 1
Reputation: 4153
Change the second where
to this:
where('end_date', '<', $old_date)
Upvotes: 0