[英]How to get primary_key of last inserted record in database with Python
[英]how to count or get record of rows, whose primary_key is not in foreign table?
我有一个数据库,其中包含两个表“产品”和“规格”。 我想计算谁的规格不在“规格”表中并且产品有重复的名称。
我试过: Product::withCount(['specifications'])->has('specifications', '<', '1')->get();
但这不起作用,花费太多时间也尝试使用分页但没有结果。
更新 1:另外请让我知道对此的 RAW 查询。
更新 2:这是产品关系代码:
public function specifications()
{
return $this->hasMany('App\Specification');
}
这是我为删除重复产品和规格而制作的 function。
public function deleteDuplicateWithCountZero() {
$duplicateProducts = Product::whereIn('name', function ( $query ) {
$query->select('name')->from('products')->groupBy('name')->havingRaw('count(*) > 1');
})->paginate(50);
foreach($duplicateProducts as $duplicateProduct) {
$results = Product::where('name', '=', $duplicateProduct->name)->withCount(['specifications'])->get();
$productCount = count($results);
foreach($results as $result) {
if($result->specifications_count == 0 && $productCount > 1) {
$product = Product::find("$result->id");
Specification::where('product_id', "$product->id")->delete();
$product->delete();
$productCount--;
}
}
}
echo "Complete"; die();
}
问题:我怎么知道所有产品及其规格在计数查询之前都被删除了,但是计数查询对所有数据都花费了太多时间。 还请建议我是否可以通过查询更正 phpmyadmin 中的这个问题。
由于规范计数始终为 0,因此您可以对查询中的值进行硬编码。 另外,不要尝试 has( has()
,而是尝试doesntHave()
Product::query()
->select('*', DB::raw('0 as specifications_count'))
->doesntHave('specifications')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.