在我的数据库中,有以下表格:
from datetime import datetime
matched_string = "2020"
past = datetime.strptime(matched_string, "%Y")
present = datetime.now()
print(past.date() < present.date())
我想要实现的是使用product_category_id对查询结果进行排序。
下面是查询。
quotes
-id
-quote_title
...
quote_items
-id
-quote_id
-product_id
products
-id
-product_name
-product_category_d
结果不显示任何错误,但顺序不正确。
报价模型:
$query = Quote::query();
$query->whereHas('quote_item' , function ($query) {
$query->whereHas('product' , function ($query) {
$query->orderBy('product_category_id');
});
});
$temp= $query->find($id);
QuoteItem模型:
class Quote extends Model
{
public function QuoteItem()
{
return $this->hasMany('app\QuoteItem');
}
}
产品型号:
class QuoteItem extends Model
{
public function Quote()
{
return $this->belongsTo('app\Quote');
}
public function Product()
{
return $this->belongsTo('app\Product');
}
}
答案 0 :(得分:3)
我建议为Quote
模型创建专用范围:
public function scopeOrderByCategory($query)
{
return $query
->join('quote_items', 'quote_items.quote_id', '=', 'quotes.id')
->join('products', 'products.id', '=', 'quote_items.product_id')
->orderBy('products.product_category_id');
}
然后,您可以在选择报价并需要按其产品类别订购它们时使用它:
$quotes = Quote::orderByCategory()->get();
但是您必须对此范围内部连接quote_items
和products
表的事实保持谨慎。
您可以阅读有关本地口才范围here的更多信息。
答案 1 :(得分:-2)