programing

Laravel 웅변가:조인된 테이블에서 특정 열만 가져오는 방법

itsource 2023. 1. 17. 21:35
반응형

Laravel 웅변가:조인된 테이블에서 특정 열만 가져오는 방법

나는 2개의 테이블, 즉 주제와 사용자를 웅변으로 연결했다.

테마 모델:

public function user() {
  return $this->belongs_to('User');
}

사용자 모델:

public function themes() {
  return $this->has_many('Theme');
}

나의 웅변 api 호출은 다음과 같습니다.

return Response::eloquent(Theme::with('user')->get());

그러면 테마의 모든 열(괜찮음)과 사용자의 모든 열(괜찮음)이 반환됩니다.사용자 모델의 'username' 열만 필요한데 어떻게 쿼리를 제한할 수 있습니까?

모형을 변경하여 선택할 열을 지정합니다.

public function user() {
  return $this->belongs_to('User')->select(array('id', 'username'));
}

가입할 칼럼도 꼭 넣어주세요.

Laravel > = 5.2의 경우

->pluck() 메서드를 사용합니다.

$roles = DB::table('roles')->pluck('title');

단일 열의 값을 포함하는 배열을 가져오려면 pluc 메서드를 사용할 수 있습니다.


Larabel <= 5.1의 경우

-> lists() 메서드를 사용합니다.

$roles = DB::table('roles')->lists('title');

이 메서드는 역할 제목 배열을 반환합니다.반환된 배열에 대해 다음과 같은 사용자 지정 키 열을 지정할 수도 있습니다.

다음과 같이 get 파라미터에 필드 배열을 지정할 수 있습니다.

return Response::eloquent(Theme::with('user')->get(array('user.username'));

업데이트(Larabel 5.2용) 문서에서 다음을 수행할 수 있습니다.

$response = DB::table('themes')
    ->select('themes.*', 'users.username')
    ->join('users', 'users.id', '=', 'themes.user_id')
    ->get();

알아요, 웅변가가 필요하지만 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();

사용자 2317976의 첫 번째 답변이 통하지 않았습니다.라벨 5.1을 사용하고 있습니다.

페이지 번호부여와 함께 사용

$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->select('themes.*', 'users.username')
->paginate(6);

다른 으로는 '먹다'를 .$hidden표시하지 않을 열을 숨기려면 모델의 속성을 선택합니다.이 속성을 즉시 정의하거나 모델에 기본값을 설정할 수 있습니다.

public static $hidden = array('password');

이제 JSON 응답을 반환할 때 사용자 암호가 숨겨집니다.

같은 방법으로 즉시 설정할 수도 있습니다.

User::$hidden = array('password');

user2317976은 관련 테이블의 열을 선택하는 훌륭한 정적 방법을 도입했습니다.

모델을 사용할 때 원하는 모든 것을 얻을 수 있도록 역동적인 방법을 찾아냈습니다.

return Response::eloquent(Theme::with(array('user' => function ($q) {
    $q->addSelect(array('id','username'))
}))->get();

이 트릭은 load()에도 유효하다는 것을 알게 되었습니다.이건 매우 편리합니다.

$queriedTheme->load(array('user'=>function($q){$q->addSelect(..)});

대상 테이블의 키도 포함해야 합니다.그렇지 않으면 찾을 수 없습니다.

이 방법:

Post::with(array('user'=>function($query){
    $query->select('id','username');
}))->get();

오래된 질문인 것은 알지만 질문 작성자처럼 API를 구축하고 있다면 출력 변압기를 사용하여 이러한 작업을 수행합니다.

Transofrmer는 실제 데이터베이스 쿼리 결과와 컨트롤러 사이의 계층입니다.사용자 또는 API 소비자에게 출력되는 내용을 쉽게 제어하고 수정할 수 있습니다.

출력 변환 레이어의 견고한 토대로서 프랙탈을 추천합니다.매뉴얼은 이쪽에서 보실 수 있습니다.

Larabel 4에서는 모델에 다음을 추가하여 특정 필드가 반환되지 않도록 숨길 수 있습니다.

protected $hidden = array('password','secret_field');

http://laravel.com/docs/eloquent#converting-to-arrays-or-json

Laravel 5.5에서 가장 깨끗한 방법은 다음과 같습니다.

Theme::with('user:userid,name,address')->get()

콜론과 선택할 필드를 쉼표로 구분하여 공백 없이 추가합니다.

모델 사용:

Model::where('column','value')->get(['column1','column2','column3',...]);

쿼리 작성기 사용:

DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);

만약 제가 이것을 잘 이해했다면, 반환되는 것은 당신이 한 칸만 보고 싶어한다는 것 빼고는 괜찮습니다.그렇다면 아래는 훨씬 더 단순해질 것입니다.

return Response::eloquent(Theme::with('user')->get(['username']));

#2개 또는 3개의 다른 테이블에서 선택한 열을 얻을 수 있습니다.

$users= DB::Table('profiles')->select('users.name','users.status','users.avatar','users.phone','profiles.user_id','profiles.full_name','profiles.email','profiles.experience','profiles.gender','profiles.profession','profiles.dob',)->join('users','profiles.user_id','=','users.id')
            ->paginate(10);

http://laravel.com/docs/database/eloquent#to-array 를 참조해 주세요.

API에 표시하지 않을 열을 정의할 수 있어야 합니다.

언급URL : https://stackoverflow.com/questions/14727038/laravel-eloquent-how-to-get-only-certain-columns-from-joined-tables

반응형