如何在laravel 5上实现这一点雄辩

时间:2017-07-21 09:12:09

标签: laravel laravel-5 eloquent

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

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的对象不可能   转换为字符串

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

2 个答案:

答案 0 :(得分:2)

第四次看$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']);
}

答案 1 :(得分:0)

这解决了我的问题,谢谢你们。

sb.Replace("{p.FirstName}", p.FirstName);