[英]how to count or get record of rows, whose primary_key is not in foreign table?
I have a database that have two tables 'products' and "specifications".我有一个数据库,其中包含两个表“产品”和“规格”。 I want to count whose specifications are not in "specifications" table and products have duplicate names.我想计算谁的规格不在“规格”表中并且产品有重复的名称。
I have tried: Product::withCount(['specifications'])->has('specifications', '<', '1')->get();
我试过: Product::withCount(['specifications'])->has('specifications', '<', '1')->get();
but this is not working, taking too much time also tried with paginate but get no result.但这不起作用,花费太多时间也尝试使用分页但没有结果。
Update 1: Also please let me know the RAW query for this.更新 1:另外请让我知道对此的 RAW 查询。
Update 2: Here is the Product Relation code:更新 2:这是产品关系代码:
public function specifications()
{
return $this->hasMany('App\Specification');
}
Here is the function I made for deleting duplicate products and there specifications.这是我为删除重复产品和规格而制作的 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();
}
Problem: How can I know all products and their specifications are deleted until count query, But count query taking too much time for all data.问题:我怎么知道所有产品及其规格在计数查询之前都被删除了,但是计数查询对所有数据都花费了太多时间。 Please also suggest if I can correct this thing in phpmyadmin with a query.还请建议我是否可以通过查询更正 phpmyadmin 中的这个问题。
Since the specification count is always going to be 0, you could hardcode the value in the query.由于规范计数始终为 0,因此您可以对查询中的值进行硬编码。 Also, instead of has()
, try doesntHave()
另外,不要尝试 has( has()
,而是尝试doesntHave()
Product::query()
->select('*', DB::raw('0 as specifications_count'))
->doesntHave('specifications')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.