Php 在laravel上使用带条件的insert

Php 在laravel上使用带条件的insert,php,laravel,Php,Laravel,我想在“ta”和“tb”int列中插入值,并附带一些条件。我有这个控制器 public function save() { $book = new Book; $ta = DB::select('SELECT MAX(ta) from book'); if ($ta == 0) { DB :: insert('insert into book (ta, tb) values (?, ?)', array(1, 1)); }else{ $tb = DB

我想在“ta”和“tb”int列中插入值,并附带一些条件。我有这个控制器

public function save()
{
$book = new Book;

$ta = DB::select('SELECT MAX(ta) from book');
if ($ta == 0) { 
        DB :: insert('insert into book (ta, tb) values (?, ?)', array(1, 1));
    }else{
        $tb = DB :: select('select max(tb) from book where ta = ?', array('$ta'));
        if ($tb <= 20) {
            DB :: insert('insert into book (ta, tb) values (ta=?, tb=?)', array('$ta', '$tb' + 1));
        }else{
            DB :: insert('insert into book (ta, tb) values (ta=?, tb=?)', array('$ta' + 1, 1));
        }
    }
$book->ta = $ta;
$book->tb = $tb;
$book->save();
}

我如何解决这个问题?

它插入两次的原因是您创建了一个DB::insert,并使用$book->save创建了一本新书

这应该更好地发挥作用:

$book = new Book;
$ta = DB::table('book')->selectRaw('MAX(ta) AS ta')->first()->ta;
if($ta == 0){
    $book->ta = 1;
    $book->tb = 1;
}
else {
    $tb = DB::table('book')->selectRaw('MAX(tb) AS tb')
            ->where('ta', $ta)->first()->tb;
    if($tb <= 20){
        $book->ta = $ta;
        $book->tb = $tb + 1;
    }
    else {
        $book->ta = $ta + 1;
        $book->tb = 1;
    }
}
$book->save();

@lukasgeiter我在该控制器中编写了条件,结果是插入两次,列为0,然后请显示您拥有的确切代码。谢谢