What SQL is returned.
Using withCount('a')->having('a_count', '=', 0)->delete() erase all the table!
Hi.
I've got an issue which is pretty weird. I have two models with ManyToMany relationship: Website and Keyword.
I'm using KeywordController@destroy to "detach" the relation from the Website model, then I want to delete unused Keywords from the database.
I would use:
public function destroy(Website $website, Request $request)
{
$website->keywords()->detach($request->all()); // IDs are passed as an array [1, 2, 3]
Keyword::withCount('websites')
->having('websites_count','=', 0)
->get(); // Works as expected, returns just some rows
Keyword::withCount('websites')
->having('websites_count','=', 0)
->delete(); // DELETE all rows from the table!
}
The problem is Laravel just performs a "DELETE FROM keywords" (seen in Telescope) so the table is just like truncated (except that the primary key isn't reinitialized).
What is weird is when I do the same query with get() instead of delete(), I get what I expect: just some rows, not the entire table!
Why?
@romainb yeah, that's a really weird behavior, I reproduced it on my table as well.. This is what worked for me, and it is simplified.
Keyword::doesntHave('websites')->delete();
I think that problem has to do by running having() on the query, but I am not sure..
Let me know if this works for you :)
Please or to participate in this conversation.