Laravel 从其他关系调用资源关系
Laravel Resource Call Relationship from other Relationship
有没有办法获取 Laravel 资源中其他关系的关系?
我尝试这样的事情:
'customers' => $this->customers()->files()->get(),
我实际上在 Products 里面。产品有很多客户,客户也有很多文件。我想做的是获取客户文件。有解决办法吗?
尝试
$this->customers()->with('files')->get()
如果建立了适当的关系,应该可以工作。
编辑:
获得计数的最简单解决方案也是
$this->customers()->with('files')->withCount('files')->get()
假设这些是您的模型
class Products extends Model
{
public function customers(){
return $this->hasMany(Customers::class, 'product_id');
}
}
class Customers extends Model
{
public function files(){
return $this->hasMany(Files::class, 'customer_id');
}
}
访问一个客户的所有文件($this is product)
$customers = $this->customers;
foreach($customers as $customer){
$file = $customer->files;
}
如果您想访问所有客户的所有文件,您可以向您的产品模型添加另一种方法,如下所示和 $files = $product->files
class Products extends Model
{
public function customers(){
return $this->hasMany(Customers::class, 'product_id');
}
public function files(){
return $this->hasManyThrough(Files::class, Customers::class);
}
}
有没有办法获取 Laravel 资源中其他关系的关系? 我尝试这样的事情:
'customers' => $this->customers()->files()->get(),
我实际上在 Products 里面。产品有很多客户,客户也有很多文件。我想做的是获取客户文件。有解决办法吗?
尝试
$this->customers()->with('files')->get()
如果建立了适当的关系,应该可以工作。
编辑:
获得计数的最简单解决方案也是
$this->customers()->with('files')->withCount('files')->get()
假设这些是您的模型
class Products extends Model
{
public function customers(){
return $this->hasMany(Customers::class, 'product_id');
}
}
class Customers extends Model
{
public function files(){
return $this->hasMany(Files::class, 'customer_id');
}
}
访问一个客户的所有文件($this is product)
$customers = $this->customers;
foreach($customers as $customer){
$file = $customer->files;
}
如果您想访问所有客户的所有文件,您可以向您的产品模型添加另一种方法,如下所示和 $files = $product->files
class Products extends Model
{
public function customers(){
return $this->hasMany(Customers::class, 'product_id');
}
public function files(){
return $this->hasManyThrough(Files::class, Customers::class);
}
}