【问题标题】:Laravel - with relation conditionLaravel - 具有关系条件
【发布时间】:2021-03-10 09:20:10
【问题描述】:

试图在模型关系中集成“如果条件”。 但它不起作用。

    $customer_index = Customer::where('firm_id', $firm_id)
    ->with(['company', 'tires', 'vehicles'])
    ->withCount(['tires', 'vehicles'])
    ->orderBy('id', 'desc');

我的 Customer.php 模型

public function vehicles()
{
    if(isset($this->company->is_fleet)){
        return $this->hasMany('App\Models\CustomerVehicle', 'fleet_id', 'company_id');
    }
    return $this->hasMany('App\Models\CustomerVehicle');
}

【问题讨论】:

标签: laravel eloquent


【解决方案1】:

不能用急切加载来做那种条件。

为了保持 eloquent 的所有好处,你应该分离关系

public function company_vehicles()
{
    return $this->hasMany(CustomerVehicle::class, 'fleet_id', 'company_id');
}

public function customer_vehicles()
{
    return $this->hasMany(CustomerVehicle::class);
}

//A scope to tuck away the eager loads
public function scopeVehicles($query)
{
   return $query->with(['company_vehicles', 'customer_vehicles']);
}

您在评论中要求将关系归入一键vehicles。这就是你可以尝试的方法


User::vehicles()->get()->map(function($user){

    if(!empty($user->customer_vehicles)){
      
      $user->vehicles = $user->customer_vehicles;
      unset($user->customer_vehicles);
      unset($user->company_vehicles);
      
    } else if(!empty($user->company_vehicles)) {
      
      $user->vehicles = $user->company_vehicles;
      unset($user->customer_vehicles);
      unset($user->company_vehicles);
      
    }
  
  return $user;
});

【讨论】:

  • 谢谢。但它给出:调用未定义的方法 Illuminate\Database\Eloquent\Builder::getRelated() 错误。
  • 您可以在堆栈跟踪中找到错误的哪一行。您是否正在导入 CustomerVehicle 的使用声明
  • 调用未定义的方法 Illuminate\Database\Eloquent\Builder::getRelated();供应商/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
  • 我的意思是在堆栈跟踪中查找错误发生在您编写的代码的哪一行而不是堆栈中的框架组件
  • 好的,它返回 2 个列表。 customer_vehicles 和 company_vehicles。反正没有用同一个键返回它们吗?示例:车辆:[{ bla bla bla}]。现在,它给出了 customer_vehicles: [{bla bla}], company_vehicles: [{ bla bla}]
猜你喜欢
  • 2020-10-24
  • 2019-10-12
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多