仅从连接表中

时间:2015-11-23 02:55:29

标签: php mysql laravel laravel-5 eloquent

首先我有这个'用户'模型

<?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');
    }

}

和这个'users_details'模型

<?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');
       }
}

我试图只获取'user_details'模型中的特定列('user_details [foreign key = user_id]'模型与'User [primary key / reference key = user_id]'模型的关系)

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

但不幸的是,遗憾的是,没有工作,我得到了这个错误(参见下文)

  

Connection.php第624行中的QueryException:SQLSTATE [42S22]:列不是   发现:1054'字段列表'中的未知列'users_details.phone'(SQL:   从users选择user_idusers_detailsphoneusers

请提出任何想法,帮助,线索,建议和建议吗?

1 个答案:

答案 0 :(得分:2)

试试这个,

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

希望它有效。