当我使用有许多没有选择时,它返回userTrancastion表中的所有字段
Invoicemodule.php
$invoice = UserInvoiceDetail::with('transaction')
->select('Id','UserId','TotalPrice')
->where('UserId','=',$playerId)
->get();
return $invoice;
UserInvoiceDetail.php
class UserInvoiceDetail extends Model
{
protected $table = 'user_invoice_details';
protected $primaryKey ='Id';
public function transaction()
{
return $this->hasMany(UserTransaction::class, 'InvoiceId');
}
}
输出
"Invoices":
[
{
"Id": 1,
"UserId": 5,
"TotalPrice": 110,
"transaction": [
{
"Id": 1,
"InvoiceId": 1,
"UserId": 5,
"ReferenceTransactionId": null,
"CategoryId": 1,
"ProductId": 140,
"Price": 5,
"Quantity": 5,
"CustomerId": 1,
},
{
"Id": 2,
"InvoiceId": 1,
"UserId": 5,
"ReferenceTransactionId": null,
"CategoryId": 2,
"ProductId": 3,
"Price": 15,
"Quantity": 3,
"CustomerId": 1,
}
]
}
]
但是当我使用有很多选项时,它不会返回任何userTrancastion表
UserInvoiceDetail.php
class UserInvoiceDetail extends Model
{
protected $table = 'user_invoice_details';
protected $primaryKey ='Id';
public function transaction()
{
return $this->hasMany(UserTransaction::class, 'InvoiceId')->select('user_transactions.Id','user_transactions.ProductId');
}
}
输出
"Invoices": [
{
"Id": 1,
"UserId": 5,
"TotalPrice": 110,
"transaction": []
},
{
"Id": 2,
"UserId": 5,
"TotalPrice": 110,
"transaction": []
}
]
为什么会发生这种情况,我想在事务()函数中使用join,所以我只需要选择性字段。 如何使用hasmany()选择? 提前谢谢。
答案 0 :(得分:4)
关系需要与之相关的列添加 .Select(g =>
{
var groupedDocuments = normalDocuments
.Where(x => x.DetailId == g.Key.DetailId)
.GroupBy(x => x.PersianMonth)
.ToDictionary(x => x.Key,
x => new DepositTypes(x.Sum(y=>y.Debit), x.Sum(y=>y.Credit));
Func<int, bool, decimal> getValueFunc = (id, isDebit)
=> groupedDocuments.TryGetValue(id, out var value)
? (isDebit ? value.Debit ?? value.Credit)
: 0;
return new AccountsAgingViewModel
{
DetailId = g.Key.DetailId,
DetailCode = g.Key.DetailCode,
DetailDescription = g.Key.DetailDescription,
FarvardinDebit = getValueFunc(1, isDeposit: true);
OrdibeheshtDebit = getValueFunc(2, isDeposit: true);
// etc.
};
}
private class DepositTypes
{
public decimal Debit { get; }
public decimal Credit {get; }
public DepositTypes(decimal debit, decimal credit)
{
Debit = debit;
Credit = credit;
}
}
此外,它不需要添加InvoiceId
user_transactions