我正在使用 Dingo API 在 Laravel 5.2 中创建 API 并让 Controller 返回数据
return $this->response->paginator($rows, new SymptomTransformer, ['user_id' => $user_id]);
但是,我不知道如何在 SymptomTransformer 中检索 user_id
值!尝试了许多不同的方法并尝试研究类(class),但我对 Laravel 和 OOP 都比较陌生,所以如果有人能指出我正确的方向,我将不胜感激。
下面是我的转换器类。
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}
最佳答案
您可以将额外的参数传递给转换器构造函数。
class SymptomTransformer extends TransformerAbstract
{
protected $extra;
public function __construct($extra) {
$this->extra = $exta;
}
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->extra);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}
然后调用
return $this->response->paginator($rows, new SymptomTransformer(['user_id' => $user_id]));
关于php - Laravel 分形转换器,如何传递和获取额外变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41595129/