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

前端 未结 15 2433
礼貌的吻别
礼貌的吻别 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:12

    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.

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

    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.

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

    Using with pagination

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

    Using Model:

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

    Using Query Builder:

    DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);
    
    0 讨论(0)
  • 2020-12-02 08:25

    Change your model to specify what columns you want selected:

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

    And don't forget to include the column you're joining on.

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

    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.

    0 讨论(0)
提交回复
热议问题