【问题标题】:Get ids array from related laravel model which is having belongsToMany relationship从具有 belongsToMany 关系的相关 laravel 模型中获取 ids 数组
【发布时间】:2015-11-12 09:58:16
【问题描述】:

我有一个属于许多用户的模型角色。

Class Role {
     public $fillable = ["name"];

     public function users()
     {
          return $this->belongsToMany('App/Models/User')->select(['user_id']);
     }
}

当我在角色中使用 with 查询检索用户时。我希望它只返回 user_ids 数组

 Role::with("users")->get();

它应该返回以下输出

 [ 
   {
     "name": "Role1",
     "users" : [1,2,3]
   },
   {
     "name": "Role2",
     "users" : [1,2,3]
   }
 ]

目前它给出以下输出

[ 
   {
     "name": "Role1",
     "users" : [
        {
           user_id : 1
        },
        {
           user_id : 2
        },

        {
           user_id : 3
        }
   },
   {
     "name": "Role2",
     "users" : [
        {
           user_id : 1
        },
        {
           user_id : 2
        },

        {
           user_id : 3
        }
     ]
   }
 ]

【问题讨论】:

  • 您也许可以使用->lists('user_id') 而不是->all() 来实现它。
  • 试试这个 return $this->belongsToMany('App/Models/User')->lists('user_id');
  • 对不起,我使用的是“->get”而不是“->all”。我已经编辑了我的问题。 @Jeemusu,它为所有记录提供 id 数组,我需要每个角色的 user_ids
  • @Creator 我尝试过使用列表但不起作用

标签: php mysql laravel eloquent relationship


【解决方案1】:

就我个人而言,我不会更改 users() 关系,但可能会为用户 ID 添加访问器

class Role {
    protected $fillable = ["name"];

    // adding the appends value will call the accessor in the JSON response
    protected $appends = ['user_ids'];

    public function users()
    {
         return $this->belongsToMany('App/Models/User');
    }

    public function getUserIdsAttribute()
    {
        return $this->users->pluck('user_id');
    }
}

那么您仍然有工作关系,但可以在角色响应中以数组的形式访问用户 ID。如果这对您不起作用,正如@Creator 所提到的,您可能只需在关系中添加->pluck('id') 而不是select()

【讨论】:

  • 在 Laravel 5.5+ 中我需要做 return $this->users->pluck('pivot.user_id'); 或者只是使用“id”。
  • 这很慢 - 您正在使用 $this->users->pluck() 访问它应该是 $this->users()->pluck('feild')->get()
  • @AndrewMcLagan 呃,不,调用 $this->users() 返回查询生成器。调用 $this->users 返回急切加载的集合。您可以使用$this->users()->pluck('field'),但在重复查询时会更慢。
  • here 这些人使用了$this->users()->allRelatedIds();。 @benJ,您的提示是否也适用于此?
  • 对两者都进行了测试,他们为我提出了不同的查询:1) pluck 似乎做了这个长查询:select agents.*, agent_price_table.price_table_id as pivot_price_table_id, agent_price_table.agent_id as pivot_agent_id from agents inner join agent_price_table on agents.id = agent_price_table.agent_id where agent_price_table.price_table_id = 20; 2) 而allRelatedIds 非常短:select agent_id from agent_price_table where price_table_id = 20。但显然两者都进行了额外的查询。
猜你喜欢
  • 2021-07-28
  • 2016-08-20
  • 2017-02-04
  • 2018-05-19
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多