Ubuntu Man
Ubuntu Man

Reputation: 50

Set a row to 1 while others to 0 expressed in Eloquent

Cardholders can have but one primary credit card in mysql table. 1 if using for primary and other not in use value is 0.

What I need is:

UPDATE credit_cards SET primary=IF(id=cardholder_id, 1, 0)

What I have so far is:

$cardholder_id = Input::get('cardholder_id');
$card_id = Input::get('card_id'); // For updating that specific card
$result = DB::table('creditcards')
    ->where('cardholder_id', '=', $cardholder_id)
    ->update(['primary' => 0]);
// Now I have to do another query for updating chosen $card_id 'primary' attribute to 1

I need this expressed in eloquent or query builder in one query if possible. Thank you so much in advance.

Upvotes: 0

Views: 31

Answers (1)

patricus
patricus

Reputation: 62368

For your given code, all you would need to do change your update statement:

$result = DB::table('creditcards')
    ->where('cardholder_id', '=', $cardholder_id)
    ->update(['primary' => DB::raw('IF(id='.$card_id.', 1, 0)')]);

For a more Laravel-ish solution, if you have your models and relationships setup correctly, you could extract this logic into a method on your Cardholder model:

class Cardholder extends Eloquent {
    public function creditcards() {
        return $this->hasMany('Creditcard');
    }

    public function setPrimary($cardId) {
        return $this->creditcards()->update(['primary' => DB::raw('IF(id='.$cardId.', 1, 0)')]);
    }
}

Then your code would be:

$cardholder_id = Input::get('cardholder_id');
$card_id = Input::get('card_id');
$result = Cardholder::find($cardholder_id)->setPrimary($card_id);

Upvotes: 1

Related Questions