我的模型有以下場景。通過「父」模型(Descendant Models?)檢索遠程相關的模型
- 用戶有很多公司。
- 公司有很多客戶。
- 客戶有很多發票。
- 發票有很多交易。
我想實現的是,我可以調用這些$用戶>客戶,$用戶>發票上的用戶模型和$用戶>交易。該$用戶>客戶正在與hasManyThrough關係,因爲客戶表有COMPANY_ID場,然後轉到公司表,其中一個USER_ID場上存在,然後轉到用戶表和檢查ID字段。這幾乎就像customers-> companies-> user這意味着它從每個客戶到公司,然後到公司所有者(用戶)。這意味着我希望發票 - >客戶 - >公司 - >用戶和交易 - >發票 - >客戶 - >公司 - >用戶。
現在發票和交易表沒有USER_ID或COMPANY_ID場,這意味着我不能只放在一個hasManyThrough據我所知。目前,我正在逐一檢索發票和交易,並將它們存儲在我返回的集合中。
所以我的問題是要弄清楚如何從所有發票回溯找到所有者(用戶模型),這將需要發票的客戶,從客戶到公司,而不是從公司到用戶。
invoices - customer_id (Go to the Customers table)
customers - company_id (Continue to the Companies table)
companies - user_id (Continue to the Users table)
users - id (This should now return all invoices)
transactions - invoice_id (Go to the Invoices table)
invoices - customer_id (Continue to the Customers table)
customers - company_id (Continue to the Companies table)
companies - user_id (Continue to the Users table)
users - id (This should now return all transactions)
所以,我想要的是讓那些從公司型號後代某一類型的所有型號,並返回他們的雄辯收集到能夠分頁或進一步處理它們。
這是一個模型,讓你知道我現在在做什麼。
<?php
namespace App;
class User extends Eloquent
{
// Companies Table
// - id
// - user_id
// ...
public function companies()
{
return $this->hasMany(Company::class);
}
// Customers Table
// - id
// - company_id
// ...
public function customers()
{
return $this->hasManyThrough(Customer::class, Company::class);
}
// Invoices Table
// - id
// - customer_id
// ...
public function invoices()
{
$invoices = new collect([]);
foreach ($this->customers as $customer) {
$invoices = $invoices->merge($customer->invoices);
}
return $invoices;
}
// Transactions Table
// - id
// - invoice_id
// ...
public function transactions()
{
$transactions = collect([]);
foreach ($this->invoices() as $invoice) {
$transactions->push($invoice->transaction);
}
return $transactions;
}
}
任何關係,這仍然不會讓我訪問是通過公司和客戶與用戶的所有發票或交易。 我需要這樣的'$ this-> hasManyThrough(Invoice :: class,Customer :: class,Company :: class);'這樣Eloquent會從發票表中獲取'customer_id',而不是'company_id '從客戶表中,最後從公司表中找到'user_id',以找到所有屬於用戶的用戶,因爲發票與用戶沒有直接關係。 –