Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updated_at column ambigious while updating with eloquent

I have 3 table cart,pharmacy and cart_pharmacies

cart table

cart_id | user_id | total_price | status | created_at | updated_at

pharmacy table

pharmacy_id | name | address_id | created_at | updated_at

cart_pharmacies table

cart_pharmacies_id | cart_id | pharmacy_id | created_at | updated_at

In cart modal i define relation

   public function pharmacy()
    {
        return $this->belongsToMany('App\Pharmacy','cart_pharmacies','cart_id','pharmacy_id');
    }

In parmacy modal i define

public function cart()
{
    return $this->belongsToMany('App\Cart','cart_pharmacies','pharmacy_id','cart_id');
}

In controller i have pharmacy_id i am trying to update cart status with code

$pharmacy_id=$request->input('pharmacy_id');
$pharmacy=  Pharmacy::findOrFail($pharmacy_id);
$pharmacy->cart()->update(['status'=>1]);

but it is giving me error

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 
'updated_at' in field list is ambiguous (SQL: update `cart` inner join 
`cart_pharmacies` on `cart`.`cart_id` = `cart_pharmacies`.`cart_id` set 
`status` = 1, 
`updated_at` = 2016-05-31 07:14:47 where `cart_pharmacies`.`pharmacy_id` = 5)
like image 838
Umar Akbar Avatar asked Jan 26 '26 08:01

Umar Akbar


2 Answers

SQL query error says there is multiple columns named 'updated_at' (both main and related tables) and cant decide which to update. It is a bug and I think there is no way to solve with eloquent as updated_at will be added at the end automatically without the table name specified.

like image 179
muratyuksel Avatar answered Jan 27 '26 20:01

muratyuksel


$pharmacy->cart()->toBase()->update(['status'=>1, 'cart.updated_at' => now()]);

Use toBase() method and add 'cart.updated_at' => now() to update data

like image 36
Josh Alecyan Avatar answered Jan 27 '26 21:01

Josh Alecyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!