我的数据库中有一个布尔列,用于图像缩略图。选定的一行将是缩略图(并将具有值1
),其他行将是0
。如何将选定的行值更新为1
和其他0
。
当我运行此更新功能时,它将每次根据ID(偏离路线)更新该行。
public function update(Request $request, $id)
{
$id = (int) $id;
$image = HotelGallery::where('id', $id)
->update(['is_thumbnail' => '1']);
return response()->json(['success' => 'Done']);
}
ID 2
和3
的值为1
,我如何针对 ID 来更新此 is_thumbnail 行, {1}}是3
,而其他 is_thumbnail 行应该在一个查询中是1
?
答案 0 :(得分:0)
//To Update row two as shown in above image
query="UPDATE $data_base_name.$data_base_table SET `is_thumbnail`=0 WHERE `id`=2";
result=mysqli_query($conn,(query));
//To Update row two as shown in above image (being more specific)
query="UPDATE $data_base_name.$data_base_table SET `is_thumbnail`=false WHERE `id`=2";
result=mysqli_query($conn,(query));
上面的代码会将is_thumbail
的第二行更改为0,将值更改为1,将上面代码中的'false'或'0'更改为'1'或'true'。
//Update to improved question (updating all rows)
query="
UPDATE $data_base_name.$data_base_table SET `is_thumbnail`=true WHERE `id`=2;
UPDATE $data_base_name.$data_base_table SET `is_thumbnail`=false WHERE `id`!=2;";
result=mysqli_multi_query($conn,(query));
while (mysqli_next_result($conn)){;}//this is to free result set for multi query
上面的查询会将第二行设置为“ true”或“ 1”,每隔一行设置为“ false”或“ 0”。
如果您是php新手,请阅读有关SQL注入的信息!!!另请参见https://secure.php.net/manual/en/mysqli.multi-query.php
//Update to improved question (eloquent format)
Table::where('id', '=',2 )->update(['is_thumbnail' => 'true']);
Table::where('id', '!=',2 )->update(['is_thumbnail' => 'false']);
这不是在laravel中执行此操作的最佳方法,但现在应该可以使用。
答案 1 :(得分:0)
PDO示例:
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
$thumbnail_id = 2;
$sql = 'UPDATE tab SET tab.is_thumbnail = false;' . "\n" .
'UPDATE tab SET tab.is_thumbnail = true WHERE tab.id = ?';
try {
$stmt = $db->prepare($sql);
$stmt->execute([$thumbnail_id]);
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
答案 2 :(得分:0)
我了解您希望在hotel_id中只有is_thumbnail = 1:
public function update(Request $request, $id)
{
$id = (int) $id;
$hotelGallery = HotelGallery::where('id', $id)
->pluck('hotel_id')->toArray();
$hotel_id = array_get($hotelGallery, '0', 0);
// Set is_thumbnail = 0 for all image of hotel_id
HotelGallery::where('hotel_id', $hotel_id)
->update(['is_thumbnail' => 0]);
$image = HotelGallery::where('id', $id)->update(['is_thumbnail' => 1]);
return response()->json(['success' => 'Done']);
}
答案 3 :(得分:0)
最好的Laravel方法是将此功能集成到模型中:
class HotelGallery extends Model
{
protected static function boot ()
{
parent::boot();
self::saving(function($model) {
if($model->attributes['is_thumbnail'] == 1)
{
(new self)->where('hotel_id', $model->attributes['hotel_id'])->where('id', '<>', $model->attributes['id'] ?? 0)->update(['is_thumbnail' => 0]);
}
});
}
}