Get Specific Columns Using “With()” Function in Laravel Eloquent

后端 未结 13 2136
清酒与你
清酒与你 2020-11-22 16:57

I have two tables, User and Post. One User can have many posts and one post belongs to only one user

相关标签:
13条回答
  • 2020-11-22 17:48

    If you want to get specific columns using with() in laravel eloquent then you can use code as below which is originally answered by @Adam in his answer here in response of this same question :

    Post::with('user:id,username')->get();
    

    So i have used it in my code but it was giving me error of 1052: Column 'id' in field list is ambiguous, so if you guys are also facing same problem

    Then for solving it you have to specify table name before the id column in with() method as below code:

    Post::with('user:user.id,username')->get();
    
    0 讨论(0)
  • 2020-11-22 17:49
    EmployeeGatePassStatus::with('user:id,name')->get();
    
    0 讨论(0)
  • 2020-11-22 17:51

    In your Post model

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

    Original credit goes to Laravel Eager Loading - Load only specific columns

    0 讨论(0)
  • 2020-11-22 17:52

    In your Post model:

    public function userWithName()
    {
        return $this->belongsTo('User')->select(array('id', 'first_name', 'last_name'));
    }
    

    Now you can use $post->userWithName

    0 讨论(0)
  • 2020-11-22 17:52

    Try with conditions.

    $id = 1;
    Post::with(array('user'=>function($query) use ($id){
        $query->where('id','=',$id);
        $query->select('id','username');
    }))->get();
    
    0 讨论(0)
  • 2020-11-22 17:58

    When going the other way (hasMany):

    User::with(array('post'=>function($query){
        $query->select('id','user_id');
    }))->get();
    

    Don't forget to include the foreign key (assuming it is user_id in this example) to resolve the relationship, otherwise you'll get zero results for your relation.

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