Laravel与League / Fractal有很多关系

时间:2015-08-27 17:20:08

标签: laravel laravel-5 lumen

我正在努力让我的头围绕着Laravel hasManyThrough和League / Fractal变形金刚。

我有三张桌子:

Countries:
    -id (int)
    -other fields ...

Cities:
    -id (int)
    -country_id (int)
    -other fields ...

Users
    -id (int)
    -city_id (string)
    -some other ...

我试图通过城市表关系访问来自国家/地区的用户关系,该关系正在使用以下Eloquent查询:

$countryUsers = Country::with('users')->where('id', $id)->get();

但是当我尝试使用$ fractal来转换这种关系时,我得到分段错误(核心转储)错误。

在国家控制器中我有:

class CountryController extends ApiController
{

     protected $manager;

        function __construct(Manager $manager) {

            $this->manager = $manager;

        }

    public function show(CountryTransformer $countryTransformer, $id) {


        $country = Country::find($id);

        return $this->respondItem($country, $countryTransformer);


    }


    public function respondItem($item, $transformer)

        {

            $this->manager->setSerializer(new CustomArraySerializer());

            $resource = new Item($item, $transformer);

            $data = $this->manager->createData($resource)->toArray();

            return $this->respond($data);

        }

在我的国家模特中,我有:

public function users() {

    return $this->hasManyThrough('App\Models\User', 'App\Models\City');
}

public function cities() {

    return $this->hasMany('App\Model\City');
}

城市模型:

 public function country() {
        return $this->belongsTo('App\Models\Country');
    }

用户模型:

 public function city()
    {
        return $this->belongsTo('App\Models\City');
    }

和分形国家变压器:

<?php namespace App\Transformers;


use App\Models\Country;

use League\Fractal\TransformerAbstract;

class CountryTransformer extends TransformerAbstract {

    protected $defaultIncludes = [
        'users'
    ];

    public function transform(Country $country)
    {
        return [
            'id'            => $country->id,
            'name'          => $country->name,
            'code'          => $country->code,
            'time_zone'     => $country->time_zone,
            'active'        => $country->active,
            'status'        => $country->status,
            'params'        => $country->params
        ];
    }

    public function includeUsers(Country $country)
    {

        $users = $country->users;

        if ($users) {
            return $this->collection($users, new UserTransformer());
        }
    }

}

如果有人能指出我正确的方向,我真的很感激。感谢。

0 个答案:

没有答案