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

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

    Another option is to make use of the $hidden property on the model to hide the columns you don't want to display. You can define this property on the fly or set defaults on your model.

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

    Now the users password will be hidden when you return the JSON response.

    You can also set it on the fly in a similar manner.

    User::$hidden = array('password');
    
    0 讨论(0)
  • 2020-12-02 08:37

    This is how i do it

    $posts = Post::with(['category' => function($query){
            $query->select('id', 'name');
          }])->get();
    

    First answer by user2317976 did not work for me, i am using laravel 5.1

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

    For Laravel >= 5.2

    Use the ->pluck() method

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

    If you would like to retrieve an array containing the values of a single column, you may use the pluck method


    For Laravel <= 5.1

    Use the ->lists() method

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

    This method will return an array of role titles. You may also specify a custom key column for the returned array:

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