在我的应用程序中,我一直在获取 Eloquent 查询的结果并通过转换器传输它,并且运行良好。这就是我正在做的事情:
public function index()
{
$users = User::with('profile', 'location', 'role')->get();
return $this->respond([
'data' => $this->userTransformer->transformCollection($users->all())
]);
}
但是,我遇到了一种情况,要生成嵌套资源,我需要使用 DB::RAW 查询
public function byLoan($id)
{
$users = DB::select( DB::raw("SELECT * FROM users WHERE id IN (SELECT DISTINCT(user_id) FROM farms WHERE user_id = {$id})") );
return $this->respond([
'data' => $this->userTransformer->transformCollection($users->all())
]);
}
上面的代码给了我这个错误“Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR) Call to a member function all() on array”。
我将transformCollection($users->all())更改为transformCollection($users),现在错误是“Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR) Cannot use object of type stdClass as array”。
我不知道还能尝试什么。
我的 Transformer 类如下所示:
<?php namespace Acme\Transformers;
abstract class Transformer {
public function transformCollection(array $items)
{
return array_map([$this, 'transform'], $items);
}
public abstract function transform($item);
}
以及 UserTransformer 的实现:
<?php namespace Acme\Transformers;
class UserTransformer extends Transformer
{
public function transform($arr)
{
//return $arr;
return [
'id' => $arr['id'],
'username' => $arr['username'],
'abr' => $arr['abr'],
'email' => $arr['email'],
'phone' => $arr['phone'],
'role_id' => $arr['role_id'],
'role_abr' => $arr['role']['abr'],
'role' => $arr['role']['role'],
'loc_id' => $arr['location']['id'],
'loc_abr' => $arr['location']['loc_abr'],
'region_id' => $arr['location']['region_id'],
'is_admin' => (boolean) $arr['is_admin'],
'is_manager' => (boolean) $arr['is_manager'],
'show_agency' => (boolean)$arr['profile']['show_agency'],
'show_balance_due' => (boolean)$arr['profile']['show_balance_due'],
'show_close_date' => (boolean)$arr['profile']['show_close_date'],
'show_commit_arm' => (boolean)$arr['profile']['show_commit_arm'],
'show_region' => (boolean)$arr['profile']['show_region'],
'show_season' => (boolean)$arr['profile']['show_season']
];
}
}
首先,不要在
all()
上使用 DB::select
。 select 方法在被调用后立即执行查询。另外 all()
仅适用于 Eloquent 模型。
然而,这里更大的问题是“查询生成器”结果的结构。它是一个数组(所有行),其中填充了对象(单独的行,每列的属性) 这意味着,将其传递给转换方法,然后像关联数组一样访问
columns是行不通的。示例:
$arr['id']
您需要做的是:
$arr->id // obviously the name $arr doesn't make any sense now because its an object..
如果这扰乱了
transform()
的其他用法,你也应该只需添加
就可以了
$arr = (array) $arr;
在函数的开头。这会将对象转换为数组并确保您可以像
$arr['id']
一样访问它