Php Laravel雄辩的查询改进
目前我有一个雄辩的问题:Php Laravel雄辩的查询改进,php,laravel,eloquent,Php,Laravel,Eloquent,目前我有一个雄辩的问题: $products = Product::where('is_send', 1)->with(['articles.stock' => function($query) { $query->where('quantity', '>', 0); }])->get(); 我想知道有没有更好的方法 如需澄清: 一个产品有许多文章 一篇文章有一只股票 我需要article\u id其中product是\u
$products = Product::where('is_send', 1)->with(['articles.stock' => function($query) {
$query->where('quantity', '>', 0);
}])->get();
我想知道有没有更好的方法
如需澄清:
一个产品有许多文章
一篇文章有一只股票
我需要
article\u id
其中product是\u send=1并且该产品的article有数量>那么0
如果您经常进行此查询,那么您可以创建一个范围,下面是一个示例:
产品型号代码
public function scopeltStockQuantity($query, $quantity) {
return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
$innerQuery->where('quantity', '>', $quantity);
}]);
}
public function scopeltQuantity($query, $quantity) {
return $query->where('quantity', '>', $quantity);
}
public function scopeltStockQuantity($query, $quantity) {
return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
$innerQuery->ltQuantity($quantity);
}]);
}
然后你可以做:
$products = Product::where('is_send', 1)->ltStockQuantity(0)->get();
或者,要进一步分离代码,可以执行以下操作:
股票型号代码
public function scopeltStockQuantity($query, $quantity) {
return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
$innerQuery->where('quantity', '>', $quantity);
}]);
}
public function scopeltQuantity($query, $quantity) {
return $query->where('quantity', '>', $quantity);
}
public function scopeltStockQuantity($query, $quantity) {
return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
$innerQuery->ltQuantity($quantity);
}]);
}
产品型号代码
public function scopeltStockQuantity($query, $quantity) {
return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
$innerQuery->where('quantity', '>', $quantity);
}]);
}
public function scopeltQuantity($query, $quantity) {
return $query->where('quantity', '>', $quantity);
}
public function scopeltStockQuantity($query, $quantity) {
return $query->with(['articles.stock' => function($innerQuery) use ($quantity) {
$innerQuery->ltQuantity($quantity);
}]);
}
这有用吗??在问题中添加表列信息如果您可以按某些内容筛选文章,这将是一件好事,但如果不是,则可能是此查询或3表联接。3表联接可能会稍微快一点。然而问题是,股票真的需要从文章中分离出来吗?因为它看起来是1到1。我同意@apokryfos的观点,你最好接受你提出的查询,你所能做的就是通过创建一个范围来优化它。如果你正在使用或将要大量使用它,这一点适用