在我的模型中,我有下面的场景。
我想要实现的是,我可以在用户模型上调用这些$user->customers,$user->invoices和$user->transactions。$user->customers正在处理一个hasManyThrough关系,因为customers表有一个company_id字段,该字段随后转到companies表,其中存在user_id字段,该字段随后进入usersE 229表,并检查E 130idE 231字段。这非常类似于customers->companies->user,这意味着它从每个客户到公司,然后到公司所有者(用户)。这意味着我希望invoices->customers->companies->user和transactions->invoices->customers->companies->user.
现在,transactions发票、和表没有user_id或company_id字段,这意味着据我所知,不能只输入hasManyThrough。目前,我正在检索transactions和的发票,并将它们存储在我返回的集合中。
因此,我的问题是,如何从所有发票中回溯,以找到所有者(用户模型),这将需要去客户的发票,从客户到公司,而不是从公司到用户。
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;
}
}发布于 2016-11-09 18:50:37
使用belongsTo关系可以很容易地做到这一点。
这些应该使您能够在中间执行$transaction->user或任何关系。
class Transaction extends Model
{
public function invoice()
{
return $this->belongsTo(Invoice::class);
}
public function customer()
{
return $this->invoice->customer();
}
public function company()
{
return $this->customer->company();
}
public function user()
{
return $this->company->user();
}
}
class Invoice extends Model
{
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function company()
{
return $this->customer->company();
}
public function user()
{
return $this->company->user();
}
}
class Customer extends Model
{
public function company()
{
return $this->belongsTo(Company::class);
}
public function user()
{
return $this->company->user();
}
}
class Company extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}https://stackoverflow.com/questions/40510016
复制相似问题