sahar_mkr's avatar

eloquent with filter

Hi everyone, I want to use a custom filter, I wrote an abstract filter and all other filters extend from it, now I want to put created_at as a filter and make my query according to it, but I have this error: Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in where clause, my query is :

$p = Customer::whereHas('transactions', function($query) use($request) {
        $query->filter($request);
    })->count();

because I have created_at in both tables transactions and customers, this doesn't accept my filter, I need this filter in my query, do you have any suggestions, can I use select and rename created_at on it? thanks a lot

0 likes
1 reply
LaryAI's avatar
Level 58

The error message suggests that the created_at column is ambiguous because it exists in both the transactions and customers tables. To resolve this, you can specify which table's created_at column you want to use in the whereHas method by prefixing it with the table name or alias. Here's an example:

$p = Customer::whereHas('transactions', function($query) use($request) {
        $query->where('transactions.created_at', '>', $request->input('created_at'));
    })->count();

In this example, we're using the where method to add a condition to the transactions relationship query. We're specifying the transactions.created_at column to avoid ambiguity. You can adjust the condition to fit your specific use case.

Note that if you're using a custom filter method on the query builder, you'll need to modify it to include the table name or alias for the created_at column as well.

Please or to participate in this conversation.