私は私のモデルで次のシナリオを持っています。"親"モデル(遠隔モデル)を介して遠くに関連するモデルを取得
- ユーザーは多数存在します。
- 企業には多くの顧客がいます。
- お客様には多くの請求書があります。
- 請求書には多くのトランザクションがあります。私が達成しようとしています何
は、私はUserモデルにそれらする$ user->顧客、する$ user->請求書とする$ user->取引を呼び出すことができるということです。 顧客表は、その後のuser_idフィールドは、その後に行くその存在企業テーブルに行くのcompany_idフィールドを持っているのでがhasManyThrough関係で働いているする$ user->顧客ユーザーはテーブルを開き、idフィールドを確認します。これは、のカスタマー - >企業 - >ユーザーのようになります。つまり、各顧客から会社に、次に会社の所有者(ユーザー)に移動します。これは、請求書 - >顧客 - >企業 - >ユーザーとトランザクション - >請求書 - >顧客 - >企業 - >ユーザーを希望することを意味します。
今請求書とテーブルは、私はちょうど私の知る限りhasManyThroughに入れることができないことを意味のuser_idまたはのcompany_idフィールドを持っていない取引。現時点ではの請求書との取引を1つずつ取り込み、返品するコレクションに保管しています。
私の問題は、請求書の顧客に行く必要がある所有者(ユーザーモデル)を見つけるために、すべての請求書をバックトラックする方法を理解することです。ユーザー。
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;
}
}
で
$transaction->user
または任意の関係を行うことができるできるようにする必要があります。 Eloquentが請求書テーブルから 'customer_id'を取得するために、' $ this-> hasManyThrough(Invoice :: class、Customer :: class、Company :: class); 'のようなものが必要になります。 'customersテーブルから、最後に' users_id'をcompanyテーブルから検索して、すべてのユーザが所属するユーザを見つけることができます。なぜなら、請求書はusreと直接関係していないからです。 –