SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in order clause is ambiguous Laravel 8

I just don't know what's wrong with my code and why it produces this error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in order clause is ambiguous (SQL: select * from cars inner join car_books on car_books.car_id = cars.id order by created_at desc)

Here's my code:

public function carBook()
{
    $car_books = Car::join('car_books','car_books.car_id','=','cars.id')->latest()->get();
    return view('admin.car_book',compact('car_books'));
}

Upvotes: 0

Views: 1320

Answers (2)

pullidea-dev
pullidea-dev

Reputation: 1803

You have to order by cars.created_at or car_books.created_at.

Both tables have created_at column, so it is ambiguous.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

The error is telling you that there is a created_at field in both the cars and car_books table. You need to specify exactly which of those you want to use within the order by clause. So either:

order by cars.created_at desc

Or:

order by car_books.created_at desc

Upvotes: 0

Related Questions