使用if条件的Laravel查询

时间:2017-08-01 07:49:15

标签: php laravel laravel-5.4

如果符合条件,我想将数据插入表中。下面的代码是否有这样的代码?

DB::table('food')->insert([
    'dessert' => $dessert1,
    if(beverage == 1)
        'drinks' => 1;
    else if(beverage == 2)
        'drinks' => 2;
]);
...

7 个答案:

答案 0 :(得分:2)

你可以试试这个:(食物是你的模特)

$food = new Food(); // new instance of food model
$food->dessert = $dessert1;
if(beverage == 1)
 $food->drinks = 1;
else if(beverage == 2)
 $food->drinks = 2;
$food->save();

如果条件有查询,您的处理方式如何,但根据您的问题,您可以执行以下操作:

DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks' => $beverage,
]);

答案 1 :(得分:1)

像这样使用:

<强>代码:

$drinks = 0;
if(beverage == 1)
   $drinks = 1;
else if(beverage == 2)
   $drinks = 2;

DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks'  => $drinks
]);

答案 2 :(得分:1)

一种简单的方法是将预定义值数组生成为beverage => drink

$drinks = [ 1 => 1, 2 => 2 ];

DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks' => $drinks[$beverage];
]);

答案 3 :(得分:0)

我想你可以试试这个:

if($beverage == 1){
  DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks' => 1,

]);

}

if(beverage == 2){
  DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks' => 2,

]);

}

$food = new Food;
$food->dessert = $dessert1;

if($beverage == 1){
  $food->drinks = 1;
}

if($beverage == 1){
  $food->drinks = 2;
}

$food->save();

答案 4 :(得分:0)

您需要预先确定值,并在insert外部使用if:

$values = [ "dessert" => $dessert1 ];
if($beverage == 1) //How on earth did you ever expect if (beverage == 1) to work in anything?
     $values['drinks'] = 1;
else if($beverage == 2)
    $values['drinks'] = 2;

DB::table('food')->insert($values);

您还可以使用ternary operator (?:)确定内联值:

DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks' => ($beverage==1?1:($beverage==2?2:null));
]);

在您的情况下,以下内容也可能有效:

DB::table('food')->insert([
    'dessert' => $dessert1,
    'drinks' => $beverage
]);

答案 5 :(得分:0)

你也可以像这样DB制作条件

$query = DB::table('food');

$query->insert(['dessert' => $dessert1]);

if(beverage == 1)
    $query->insert(['drinks' => 1]);
else if(beverage == 2)
    $query->insert(['drinks' => 2]);

答案 6 :(得分:0)

首先检查您的状况,这将使您的代码清晰可读 比如@RJParikh

$drinks = 0;
if(beverage == 1)
   $drinks = 1;
else if(beverage == 2)
   $drinks = 2;

或者,如果您的参赛人数有限,请执行@Zayn Ali

$drinks = [ 1 => 1, 2 => 2 ]; // $beverageValue => $drinksValue

然后使用insert -

DB::table('food')->insert([
    ......,
    ......,
]);

但请记住,如果你使用这样的插入,你必须使字段可以从模型填充。最好在食物桌上制作模型并按照@Firas Rassas回答。结合答案您的代码将如下所示 -

 $drinks = 0;
    if(beverage == 1)
       $drinks = 1;
    else if(beverage == 2)
       $drinks = 2;

    $food = new Food(); // new instance of food model
    $food->dessert = $dessert1;
    $food->drinks = $drinks;
    $food->save();