development

laravel eloquent에서 특정 열을 선택하는 방법

big-blog 2020. 9. 10. 08:13
반응형

laravel eloquent에서 특정 열을 선택하는 방법


테이블에 7 개의 열이 있고 그중 두 개만 선택하려고합니다.

SELECT `name`,`surname` FROM `table` WHERE `id` = '1';

laravel eloquent 모델에서는 다음과 같이 보일 수 있습니다.

Table::where('id', 1)->get();

하지만이 식은 id가 1 인 모든 열을 선택하고 두 개의 열 (이름, 성) 만 원합니다. 두 개의 열만 선택하는 방법은 무엇입니까?


다음과 같이 할 수 있습니다.

Table::select('name','surname')->where('id', 1)->get();

Table::where('id', 1)->get(['name','surname']);

all () 메서드를 사용하면 아래와 같이 테이블에서 특정 열을 선택할 수 있습니다.

ModelName::all('column1', 'column2', 'column3');

참고 : Laravel 5.4


다음 find()과 같이 사용할 수도 있습니다 .

ModelName::find($id, ['name', 'surname']);

$id변수는 모델의 여러 인스턴스를 검색해야하는 경우에 배열 할 수있다.


또한 Model::all(['id'])->toArray()id 만 배열로 가져옵니다.


먼저 해당 테이블을 나타내는 모델을 생성 한 다음 아래 Eloquent 방법을 사용하여 2 개 필드의 데이터 만 가져와야합니다.

Model::where('id', 1)
         ->pluck('name', 'surname')
         ->all();

get ()뿐만 아니라 all ()을 사용할 수 있습니다.

ModelName::where('a', 1)->get(['column1','column2']);

다음 코드를 사용하십시오.-

   $result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();   

사용할 수 있습니다 Table::select ('name', 'surname')->where ('id', 1)->get ().

특정 필드 만 선택할 때 나중에 요청에서 다른 필드에 액세스하는 경우 다른 쿼리를 작성해야합니다 (분명 할 수 있지만 해당 경고를 포함하고 싶음). id 필드를 포함하는 것은 일반적으로 좋은 생각이므로 laravel은 모델 인스턴스에 대한 업데이트를 다시 작성하는 방법을 알고 있습니다.


또한 뽑기를 사용할 수 있습니다.

Model::where('id',1)->pluck('column1', 'column2');

가장 일반적인 접근 방식은를 사용하는 것이지만 Model::select모델 클래스 내에서 접근 자 메서드로 정의 된 모든 속성을 렌더링 할 수 있습니다. 따라서 모델에서 속성을 정의하는 경우 :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
}

그리고 다음을 사용하십시오. TableName::select('username')->where('id', 1)->get();

사용자 이름이 아닌 first_name모두로 컬렉션을 출력 username합니다.

Better use pluck(), solo or optionally in combination with select - if you want specific columns.

TableName::select('username')->where('id', 1)->pluck('username');

or

TableName::where('id', 1)->pluck('username'); //that would return collection consisting of only username values

Also, optionally, use ->toArray() to convert collection object into array.


If you want to get single row and from the that row single column, one line code to get the value of the specific column is to use find() method alongside specifying of the column that you want to retrieve it.

Here is sample code:

ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];

From laravel 5.3 only using get() method you can get specific columns of your table:

YouModelName::get(['id', 'name']);

Or from laravel 5.4 you can also use all() method for getting the fields of your choice:

YourModelName::all('id', 'name');

with both of above method get() or all() you can also use where() but syntax is different for both:

Model::all()

YourModelName::all('id', 'name')->where('id',1);

Model::get()

YourModelName::where('id',1)->get(['id', 'name']);

You can use the below query:

Table('table')->select('name','surname')->where('id',1)->get();

->get() much like ->all() (and ->first() etc..) can take the fields you want to bring back as parameters;

->get/all(['column1','column2'])

Would bring back the collection but only with column1 and column2


you can also used findOrFail() method here it's good to used

if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..

ModelName::findOrFail($id, ['firstName', 'lastName']);

Get value of one column:

Table_Name::find($id)->column_name;

Even you can use this method with where clause:

Table_Name::where('id',$id)->first()->column_name;

참고URL : https://stackoverflow.com/questions/38172857/how-to-select-specific-columns-in-laravel-eloquent

반응형