I want to insert value to 'ta' and 'tb'(int) column with some condition. I have this controller.
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();
}
How can I resolve this?
Well the reason it inserts twice is you make an DB::insert()
and also create a new book using $book->save()
This should work better:
$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();