【问题标题】:How to achieve this on laravel 5 eloquent如何在 laravel 5 eloquent 上实现这一点
【发布时间】:2017-07-21 09:12:09
【问题描述】:

我怎样才能实现这样的目标?

public function getInformation($model) {
  $result = $model::with(['province', 'city']);

  if($model == 'App\Models\Business') {
    $result->with(['businessProvince', 'businessCity']);
  }

  $result->get();
}

// call the function
$information->getInformation(\App\Models\Business::class);

我遇到了错误

类 Illuminate\Database\Eloquent\Builder 的对象不能是 转成字符串

关于上面的示例代码。任何建议都非常感谢。

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    第四次查看后,$model 应该是一个字符串,而$result 是一个 Eloquent Builder 实例,而不是模型类的实例(因为在调用 with 时启动了一个查询)。

    所以$model == 'App\Models\Business' 我会改为$model === \App\Models\Business::class,但这不应该改变结果。

    您确定此错误来自应用程序的这一部分吗?具体是哪一行?


    原来的错误答案。

    您正在尝试将模型实例与字符串进行比较(因为 $model::with() 创建了您在 $model 参数中传递的模型类的实例)。

    您可以使用 instanceof 关键字将实例与类名 (http://php.net/manual/en/language.operators.type.php) 进行比较。

    if($model instanceof \App\Models\Business) {
        $result->with(['businessProvince', 'businessCity']);
    }
    

    【讨论】:

    • 除了上面的建议,把$result = $model::with(['province', 'city']);放在if条件的else部分。
    • 你为什么要这样做?比你必须把$model::with(['province', 'city', 'businessProvince', 'businessCity']); 这个if 部分。导致您必须在代码的同一部分提供两次省市和城市的急切负载。恕我直言,这看起来更具可读性。
    • 它对我不起作用。我的目标是重用该方法,并且只有商业模式具有“businessProvince”和“businessCity”的关系。
    • 即使我这样尝试。 $result = $model::with(['province', 'city']); $result->with(['businessProvince', 'businessCity']); $result->get();
    • 你是对的,这确实不是问题所在,我修改了答案,希望能朝着正确的方向轻推。
    【解决方案2】:

    这解决了我的问题,谢谢大家。

    public function getInformation($model) {
      $result = $model::with(['province', 'city']);
    
      if($model == 'App\Models\Business') {
        // my mistake
        //$result->with(['businessProvince', 'businessCity']);
    
        $result = $result->with(['businessProvince', 'businessCity']);
      }
    
      $result->get();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 2012-12-17
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多