欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Get ids array from related laravel model which is having belongsToMany relationship 关联关系 id 组成的数组 多对多 有大用

I have a model Role which belongs to many Users.

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

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

When I retrieve users using with query in Role. I want It would return only user_ids array

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

it should return the following output

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

Currently it gives following output

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

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

        {
           user_id : 3
        }
     ]
   }
 ]
shareimprove this question
 
   
You might be able to achieve it using ->lists('user_id') instead of ->all(). – Jeemusu Aug 19 '15 at 8:09
   
try this return $this->belongsToMany('App/Models/User')->lists('user_id'); – Anil Sharma Aug 19 '15 at 8:17
   
Sorry I have used "->get" not "->all". I have edited my question. @Jeemusu, it is giving array of ids for all records, I need user_ids per role – sp11 Aug 19 '15 at 12:04
   
@Creator I have tried using list but not working – sp11 Aug 19 '15 at 12:04
正确答案

Personally, I wouldn't change the users() relationship, but maybe add an accessor for user IDs

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')->toArray();
    }
}

Then you still have a working relationship, but can access the user IDs as an array in the Role response. If that doesn't work for you, as mentioned by @Creator, you could probably just add ->lists('id') in the relationship rather than the select()

shareimprove this answer
 
   
It's working. Thank you :) – sp11 Aug 19 '15 at 12:10

来自  https://stackoverflow.com/questions/32089782/get-ids-array-from-related-laravel-model-which-is-havin...

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

普通分类: