How to get id from tosql function
I am inserting a lot of data into a table pools
. At the same time, while I am doing this, I need to set an inactive field in the table draws
to 0 . However, I am having problems with this.
Code:
$pools = DB::table('addresses as a')
->join('incodes as i', 'i.id', '=', 'a.incode_id')
->join('draws as d', 'd.incode_id', '=', 'i.id')
->join('users as u', 'u.id', '=', 'a.user_id')
->where('d.isactive', '=', '1')
->select('u.id as user_id', 'd.id as draw_id')->distinct();
$bindings = $pools->getBindings();
$insertQuery = 'INSERT into pools (user_id, draw_id)'.$pools->toSql();
$pools = \DB::statement($insertQuery, $bindings);
foreach($pools as $pool) {
//Deactivate draw id from draws table when
//successfully inserted in pools table
Draw::where('id', $pool->draw_id)
->update(['isactive' => 0]);
}
The cycle foreach
will never work with $pools
because of the natural \DB::statement
.
So how do I set a field isactive
in a table draws
to 0
when it was inserted into tables pools
?
thank
source to share
Try the following:
Config::set('database.fetch', PDO::FETCH_ASSOC);
$pools = DB::table('addresses as a')
->join('incodes as i', 'i.id', '=', 'a.incode_id')
->join('draws as d', 'd.incode_id', '=', 'i.id')
->join('users as u', 'u.id', '=', 'a.user_id')
->where('d.isactive', '=', '1')
->select('u.id as user_id', 'd.id as draw_id')
->distinct()
->get();
Pool::insert($pools);
foreach ($pools as $pool) {
if ($draw = Draw::find($pool['draw_id'])) {
$draw->isactive = 0;
$draw->save();
}
}
source to share