it-source

ToMany 관계에 속하는 관련 래벨 모델에서 ID 배열을 가져옵니다.

criticalcode 2023. 9. 23. 22:46
반응형

ToMany 관계에 속하는 관련 래벨 모델에서 ID 배열을 가져옵니다.

저는 많은 사용자가 속한 역할 모델을 가지고 있습니다.

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

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

Role에서 쿼리와 함께 사용하는 사용자를 검색할 때.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
        }
     ]
   }
 ]

개인적으로, 저는 그것을 바꾸지 않을 것입니다.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()

언급URL : https://stackoverflow.com/questions/32089782/get-ids-array-from-related-laravel-model-which-is-having-belongstomany-relations

반응형