Laravel Eloquent: How to get only certain columns from joined tables

前端 未结 15 2445
礼貌的吻别
礼貌的吻别 2020-12-02 07:57

I have got 2 joined tables in Eloquent namely themes and users.

theme model:

public function user() {
  return $this->belongs_to(         


        
相关标签:
15条回答
  • 2020-12-02 08:26

    This Way:

    Post::with(array('user'=>function($query){
        $query->select('id','username');
    }))->get();
    
    0 讨论(0)
  • 2020-12-02 08:27

    I know, you ask for Eloquent but you can do it with Fluent Query Builder

    $data = DB::table('themes')
        ->join('users', 'users.id', '=', 'themes.user_id')
        ->get(array('themes.*', 'users.username'));
    
    0 讨论(0)
  • 2020-12-02 08:27

    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.

    0 讨论(0)
  • 2020-12-02 08:27

    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

    0 讨论(0)
  • 2020-12-02 08:30

    You can supply an array of fields in the get parameter like so:

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

    UPDATE (for Laravel 5.2) From the docs, you can do this:

    $response = DB::table('themes')
        ->select('themes.*', 'users.username')
        ->join('users', 'users.id', '=', 'themes.user_id')
        ->get();
    
    0 讨论(0)
  • 2020-12-02 08:31

    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']));
    
    0 讨论(0)
提交回复
热议问题