【问题标题】:Laravel return json with eloquent collection relationship valuesLaravel 返回具有雄辩集合关系值的 json
【发布时间】:2020-09-08 19:29:03
【问题描述】:

我在 UsersApiController 类中有以下函数:- 公共函数 getKhatmas()

{
    $user = Auth::user();
    $khatmas = $user->khatmas;
    return response()->json($khatmas);
}

上面的代码给出以下响应:-

[
    {
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": 2,
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    },
    {
        "id": 4,
        "hash": "5ec72b7005126",
        "type": 2,
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    },
]

用户模型文件中的关系函数:-

public function khatmas()
    {
        return $this->hasMany('App\Khatma');
    }

App\Khatma 文件内容:-

public function type()
    {
        return $this->belongsTo('App\KhatmaType');
    }

在上面的 json response 中,("type": 2) 是 App\KhatmaType Model 的外键。 我希望使用 KhatmaType 模型的外键而不是 json 响应,我希望它从 App\KhatmaType 返回列“标题”,如下所示:-

{
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": "this is title from App\KhatmaType Model",
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    }

`我尝试了以下方法:-

$khatmas = $user->khatmas->with('type');

但它返回错误:方法 Illuminate\Database\Eloquent\Collection::with 不存在

【问题讨论】:

  • 你可以试试这个Auth::user()->load('khatmas.type')
  • @Aslam 我试过了,我得到了 "type": null,
  • 你可以在查询中使用join,但我认为你有反向定义的关系,或者错误表中的外键'type',因为如果KhatmaType属于Khatma,外键应该在KhatmaType 而不是在 Khatma 中。

标签: php laravel eloquent


【解决方案1】:

已使用以下查询生成器修复:-

public function getKhatmas()
{
    $user = Auth::user();

    $khatmas = Auth::user()->khatmas()
    ->select('hash','type_text','status','expiry_date','type_id')
    ->with('type')->get();

    return response()->json($khatmas);
}

【讨论】:

  • 通过这种方式,您将在“类型”属性上拥有一个对象,而不是您要求的字符串。
  • @porloscerrosΨ 你是完全正确的,但现在对我来说没问题,如果我想从类型模型中获取更多数据,它似乎更具可扩展性。感谢您的宝贵时间
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 2022-01-15
  • 2018-06-19
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2022-01-12
  • 2015-03-14
相关资源
最近更新 更多