2
votes

First I have this 'User' model

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';
    protected $primaryKey = 'user_id';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['username', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function user_details(){
        return $this->hasOne('App\users_details');
    }

}

and this 'users_details' model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class users_details extends Model {

    protected $table = "user_details";


       public function ud()
       {
           return $this->belongsTo('App\User');
       }
}

and I'm trying to get only the specific columns from the 'user_details' model ('user_details [foreign key = user_id]' model is in relationship with the 'User [primary key/reference key = user_id]' model)

$users = User::with('user_details')->get(array('users.user_id', 'users_details.phone'));
dd(var_dump($users->toArray())); 

but unfortunately and sadly, not working and I get this error (refer below)

QueryException in Connection.php line 624: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users_details.phone' in 'field list' (SQL: select users.user_id, users_details.phone from users)

Any ideas, help, clues, suggestions, recommendation please?

1
please explain what you mean it's not working and maybe add errors you're gettingdavejal
try $users = User::with('user_details')->select('users.user_id', 'users_details.phone')->get();Alex Kyriakidis
@Alexandros: tried but still im getting same error "Unknown column 'users_details.phone' in 'field list' (SQL: select users.user_id, users_details.phone from users)" . any ideas?Juliver Galleto

1 Answers

2
votes

Try this,

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

Hope it works.