简体   繁体   English

将行设置为1,将其他行设置为0,以Eloquent表示

[英]Set a row to 1 while others to 0 expressed in Eloquent

Cardholders can have but one primary credit card in mysql table. 持卡人在mysql表中只能有一张主信用卡。 1 if using for primary and other not in use value is 0. 如果用于主要和其他未使用的值是1,则为1。

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. 提前非常感谢您。

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: 对于更像Laravel的解决方案,如果正确设置了模型和关系,则可以将此逻辑提取到持卡人模型的方法中:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM