我与3个表有多对多关系:
Products
Categories
ProductCategories
如何按产品获取或访问类别列表(不是ProductCategories列表)?
答案 0 :(得分:0)
我遇到了同样的问题,我通过返回JSON_QUERY解决了它
CREATE OR ALTER PROCEDURE [Account].[GetByProduct]
@ProductId
AS
BEGIN
SELECT
P.*,
PC.*
JSON_QUERY((
SELECT
C.*
FOR JSON PATH
)) AS [Categories]
FROM
[Relation] AS R
INNER JOIN [Product] AS P
ON P.[Id] = R.[ProductRef]
INNER JOIN [ProductCategory] AS PC
ON PC.[Id] = R.[ProductCategoryRef]
INNER JOIN [Category] AS C
ON C.[Id] = AR.[CategoryRef]
WHERE
P.[Id] = @ProductId
END
注意:我将重命名了column&tables以使用单数,而不是复数。
在EF Core方面,您必须使用JSON将conversion应用于列表。
答案 1 :(得分:0)
使用这一功能对我有帮助:
var result = (from pc in ProductCategories
join c in Categories on pc.CategoryId equals c.CategoryId
join p in Products on pc.ProductId equals p.ProductId
select new Category { //any selector you need in Category }).ToList();
答案 2 :(得分:0)
您可以在load related data中使用import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
和Include()
。
例如,如果我有类似的模型
ThenInclude()
按产品访问类别列表
public class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ProductCategory> ProductCategories { get; set; } = new List<ProductCategory>();
}
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ProductCategory> ProductCategories { get; set; } = new List<ProductCategory>();
}
public class ProductCategory
{
[Key]
public int ProductId { get; set; }
public Product Product { get; set; }
[Key]
public int CategoryId { get; set; }
public Category Category { get; set; }
}