【问题标题】:How to change the name of the key in eloquent response data in Laravel如何在 Laravel 中更改 eloquent 响应数据中的键名
【发布时间】:2020-12-19 09:06:51
【问题描述】:

我使用两个模型推文和用户表之间的雄辩关系。并运行这个 sn-ps:

$list = User::with('tweets')->all();
return response($list,200);

我的数据看起来像这样:

{
  id:1,
  name:John,
  tweets:
   [
    {id:1,content:"test"},
    {id:2,content:"test2"}
   ]
}

我有两个问题:

  1. 如何将响应数据中的tweets 键更改为例如comments
  2. 如何仅从推文中获取content 密钥?

【问题讨论】:

  • 我强烈建议阅读API Resources 文档。
  • 你能举个例子吗?
  • salaam daadaash。学习它没有捷径。你必须阅读。
  • 你使用集合和 API 资源吗?@mostafa-saadatnia
  • @FaridVatani 不...你能给我举个例子吗?

标签: laravel eloquent relationship


【解决方案1】:

假设这是一对多的关系

问题 1:在父模型中将 tweets() 更改为 comments()

class parent_model extends Model
{
  protected $hidden = ['primary_key'];

  public function tweets(){ //change to comments
    return $this->hasMany(Child::class);
  }
  //rest of the code
}

问题 2:User::with('comments:{foreign key must included},selected_table')->all(); 如果你想隐藏 primary_key 你最好在你的 Eloquent 模型上使用 $hidden 属性,然后你可以选择想要显示的列作为响应。 还将子模型中的关系belongsTo 函数设置为包含在$hidden 属性中。

class child_relation_model extends Model
{
  protected $hidden = ['primary_key', 'user'];

  public function user(){
    return $this->belongsTo(Parent::class);
  }
  //rest of the code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多