Laravel 自定义列,嵌套关系

Vad*_*rev 2 laravel laravel-5

我有这个模型:

案件:

class Cases extends Model {
    const UPDATED_AT = 'edit_date';
    const CREATED_AT = 'crt_date';

    protected $primaryKey = 'no';
    protected $guarded = ['no'];
    protected $table = 'assist';

    public function providers() {
        return $this->hasMany('App\CaseProviders', 'case_no');
    }

    public function claims() {
        return $this->hasMany('App\Claim', 'reference_no');
    }

}
Run Code Online (Sandbox Code Playgroud)

案例提供者:

class CaseProviders extends Model {

    public function detail() {
        //return $this->hasOne('App\Providers', 'code', 'code')->select(['code', 'name']);
        return $this->hasOne('App\Providers', 'code', 'code');
    }

}
Run Code Online (Sandbox Code Playgroud)

提供商:

class Providers extends Model {

    protected $table = 'user_cards';

    public function country() {
        return $this->hasOne('App\Country','id','country');
    }


}
Run Code Online (Sandbox Code Playgroud)

国家:

class Country extends Model {

    protected $primaryKey = 'id';
    protected $table = 'user_countries';

    public function city() {
        return $this->hasMany('App\City', 'country', 'id');
    }

}
Run Code Online (Sandbox Code Playgroud)

城市:

class City extends Model
{
    protected $table = 'user_cities';
}
Run Code Online (Sandbox Code Playgroud)

控制器中的这段代码:

$case = \App\Cases::where('no', $id)->with('providers.detail.country.city')->first();
Run Code Online (Sandbox Code Playgroud)

代码工作正常,但我不需要从每个模型中选择所有列。我只需要这个:

名称、代码 - 来自详细信息

姓名 - 来自国家/地区

名字 - 来自城市。

我怎样才能做到呢?

the*_*len 5

我还没有测试过这个,由于嵌套关系,它可能会进行更多查询,但无论如何,尝试一下不会有什么坏处:

    $case = \App\Cases::where('no', $id)->with([
        'providers.detail' => function ($query){
            $query->select('name', 'code');
        },
        'providers.detail.country' => function ($query){
            $query->select('name');
        },
        'providers.detail.country.city' => function ($query){
            $query->select('name');
        },
    ])->first();
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您只需要选择这些具有关系的字段,您可以直接在模型中选择:

public function country() {
    return $this->hasOne('App\Country','id','country')->select(['name']);
}
Run Code Online (Sandbox Code Playgroud)

注意 您必须包含id列和外部 ids 列。