我正在尝试基于此package
实施标准模型如果我按下以下标准进行连接并获取所需的颜色,则假设执行单个查询。但是它执行了两个查询
select `products`.`product_name`, `skus`.`quantity` from `products` inner join `skus` on `skus`.`products_id` = `products`.`products_id` where `products`.`products_id` = '1'380μshomestead
select * from `products` where `products`.`products_id` = '0' limit 1
为什么它只执行两个查询,我只需要执行第一个查询?
代码示例如下
public function __construct(ProductRepository $product_repository){
$this->product_repository = $product_repository;
}
public function all()
{
$data = $this->product_repository->getByCriteria(new GetProduct());
$product = $this->product_repository->find('1');
}
class getProduct implements CriteriaInterface {
public function apply($model, RepositoryInterface $repository)
{
$model = $model
->select('products.product_name', 'skus.quantity')
->where('products.products_id', '1')
->join('skus', 'skus.products_id', '=', 'products.products_id');
return $model;
}
}
Collection {#300 ▼
#items: array:2 [▼
0 => Product {#301 ▼
#primaryKey: "products_id"
#fillable: []
#connection: null
#table: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:2 [▶]
#original: array:2 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
1 => Product {#302 ▼
#primaryKey: "products_id"
#fillable: []
#connection: null
#table: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:2 [▶]
#original: array:2 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
答案 0 :(得分:4)
嗯,我想我们有一个解决方案。您正在执行2个查询
一个人在这里:
$data = $this->product_repository->getByCriteria(new GetProduct());
相对于:
select `products`.`product_name`, `skus`.`quantity` from `products` inner join `skus` on `skus`.`products_id` = `products`.`products_id` where `products`.`products_id` = '1'
另一个在这里
$product = $this->product_repository->find('1');
相对于:
select * from `products` where `products`.`products_id` = '0' limit 1
如果您的计划是使用条件然后执行查询,请更改getByCriteria
的{{1}},就像这样
pushCriteria
执行此操作,您告诉您的存储库您希望所有查询都遵循该条件中指定的内容,因此您的所有下一个查询都将使用该条件。所以,当你做$data = $this->product_repository->pushCriteria(new GetProduct());
时,你实际上会得到
$product = $this->product_repository->find('1');
希望我帮助并明确了为什么你从该代码中获得2个查询。