What exactly isn't working?
Jun 3, 2019
7
Level 1
Conditional INSERT
Hi there,
I am struggling to convert this conditional SQL into Builder code. Any help is much appreciated....
Given these inputs ['id' => 1, 'bid_id' => 2, 'bid' => 3] i want to insert if either there is not bid yet or the given bid is higher than any previous.
I've tried the SQL as-is, but cannot get it into Eloquent (at least not without making it just one big string which I'd like to avoid).
SQL:
INSERT INTO bids (id, bid_id, bid)
// given id, bid_id and bid
SELECT 1, 2, 3
WHERE
NOT EXISTS (SELECT 1 from bids where bid_id = 2)
OR
NOT EXISTS (SELECT 1 from bids where bid_id = 2 HAVING max(bid) >= 3)
$id = 1;
$bidId = 2;
$bid = 3;
$select = static::query()
->whereNotExists(function (Builder $query) use ($bidId) {
$query
->from('bids')
->selectRaw(DB::raw(1))
->where(['bid_id' => $bidId]);
})
->orWhereNotExists(function(Builder $query) use ($bidId, $bid) {
$query
->from('bids')
->selectRaw(DB::raw(1))
->where(['bid_id' => $bidId])
->havingRaw('max(bid) >= ?', [$bid]);
})
->select(DB::raw(sprintf('%d, %d, %d', $id, $bidId, $bid)));
$model = DB::table('auction_bids')->insertUsing(['user_id', 'auction_id', 'bid'], $select);
Please or to participate in this conversation.