Laravel Eloquent : 조인 된 테이블에서 특정 열만 가져 오는 방법
Eloquent에는 테마와 사용자라는 2 개의 조인 된 테이블이 있습니다.
테마 모델 :
public function user() {
return $this->belongs_to('User');
}
사용자 모델 :
public function themes() {
return $this->has_many('Theme');
}
내 Eloquent API 호출은 다음과 같습니다.
return Response::eloquent(Theme::with('user')->get());
테마의 모든 열 (괜찮음)과 사용자의 모든 열 (괜찮지 않음)을 반환합니다. 사용자 모델의 '사용자 이름'열만 필요합니다. 쿼리를 어떻게 제한 할 수 있습니까?
모델을 변경하여 선택하려는 열을 지정하십시오.
public function user() {
return $this->belongs_to('User')->select(array('id', 'username'));
}
그리고 여러분이 참여하고있는 칼럼을 포함하는 것을 잊지 마십시오.
Laravel> = 5.2의 경우
사용 > 뽑은 () - 방법
$roles = DB::table('roles')->pluck('title');
단일 열의 값을 포함하는 배열을 검색하려면 pluck 메소드를 사용할 수 있습니다.
Laravel <= 5.1의 경우
사용 -> 목록 () 방법
$roles = DB::table('roles')->lists('title');
이 메서드는 역할 제목 배열을 반환합니다. 반환 된 배열에 대해 사용자 지정 키 열을 지정할 수도 있습니다.
다음과 같이 get 매개 변수에 필드 배열을 제공 할 수 있습니다.
return Response::eloquent(Theme::with('user')->get(array('user.username'));
UPDATE (for Laravel 5.2) 문서 에서 다음을 수행 할 수 있습니다.
$response = DB::table('themes')
->select('themes.*', 'users.username')
->join('users', 'users.id', '=', 'themes.user_id')
->get();
알아요, 당신은 Eloquent를 요청하지만 Fluent Query Builder로 할 수 있습니다
$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->get(array('themes.*', 'users.username'));
이것이 내가하는 방법
$posts = Post::with(['category' => function($query){
$query->select('id', 'name');
}])->get();
user2317976의 첫 번째 답변이 나를 위해 작동하지 않았으며 laravel 5.1을 사용하고 있습니다.
또 다른 옵션은 $hidden
모델 의 속성을 사용 하여 표시하지 않을 열을 숨기는 것입니다. 이 속성을 즉시 정의하거나 모델에 기본값을 설정할 수 있습니다.
public static $hidden = array('password');
이제 JSON 응답을 반환 할 때 사용자 비밀번호가 숨겨집니다.
비슷한 방식으로 즉석에서 설정할 수도 있습니다.
User::$hidden = array('password');
페이지 매김과 함께 사용
$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->select('themes.*', 'users.username')
->paginate(6);
user2317976 has introduced a great static way of selecting related tables' columns.
Here is a dynamic trick I've found so you can get whatever you want when using the model:
return Response::eloquent(Theme::with(array('user' => function ($q) {
$q->addSelect(array('id','username'))
}))->get();
I just found this trick also works well with load() too. This is very convenient.
$queriedTheme->load(array('user'=>function($q){$q->addSelect(..)});
Make sure you also include target table's key otherwise it won't be able to find it.
This Way:
Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
I know that this is an old question, but if you are building an API, as the author of the question does, use output transformers to perform such tasks.
Transofrmer is a layer between your actual database query result and a controller. It allows to easily control and modify what is going to be output to a user or an API consumer.
I recommend Fractal as a solid foundation of your output transformation layer. You can read the documentation here.
In Laravel 4 you can hide certain fields from being returned by adding the following in your model.
protected $hidden = array('password','secret_field');
http://laravel.com/docs/eloquent#converting-to-arrays-or-json
On Laravel 5.5, the cleanest way to do this is:
Theme::with('user:userid,name,address')->get()
You add a colon and the fields you wish to select separated by a comma and without a space between them.
Using Model:
Model::where('column','value')->get(['column1','column2','column3',...]);
Using Query Builder:
DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);
If I good understood this what is returned is fine except you want to see only one column. If so this below should be much simpler:
return Response::eloquent(Theme::with('user')->get(['username']));
Check out, http://laravel.com/docs/database/eloquent#to-array
You should be able to define which columns you do not want displayed in your api.
'code' 카테고리의 다른 글
MavenArchiver.getManifest ()의 m2e 오류 (0) | 2020.08.26 |
---|---|
C #에서 IPv4 주소를 정수로 변환하는 방법은 무엇입니까? (0) | 2020.08.26 |
ViewPager.setOffscreenPageLimit (0)이 예상대로 작동하지 않습니다. (0) | 2020.08.26 |
Windows 배치 : 형식화 된 날짜를 변수로 (0) | 2020.08.26 |
bat 파일의 입력 텍스트를 마스킹 할 수 있습니까? (0) | 2020.08.26 |