2015-10-16 190 views
1

是否有任何人能够从我所基于的截图和模型建立的雄辩关系建议? enter image description hereLaravel 5.1雄辩关系

模型设置:

class Leaves extends Model 
{ 
    protected $table = 'leaves'; 

    protected $fillable = [ 
     'leave_type', 
     'user_id' 
    ]; 

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

} 

class LeaveType extends Model 
{ 
    protected $table = 'leave_type'; 

    protected $fillable = ['type_name']; 
} 

class User extends Model implements AuthenticatableContract, 
            AuthorizableContract, 
            CanResetPasswordContract 
{ 
    use Authenticatable, Authorizable, CanResetPassword; 

    protected $table = 'users'; 

    protected $fillable = ['name', 'email', 'password']; 

    protected $hidden = ['password', 'remember_token']; 

    public function leave() 
    { 
     return $this->hasMany('App\Leaves'); 
    } 

} 

目前我只能让叶细节,但需要根据

$user = User::oldest('name')->get(); 
foreach ($users as $user) { 
    $user->leave()-get(); 

} 

回答

0

的leave_type的TYPE_NAME检索叶型号:

class Leaves extends Model { 
    protected $table = 'leaves'; 

    protected $fillable = [ 
     'leave_type', 
     'user_id' 
    ]; 

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

} 

LeavesType型号:

class LeaveType extends Model { 
    protected $table = 'leave_type'; 

    protected $fillable = ['type_name']; 
    public function Leaves() 
    { 
     return $this->hasMany('App\Leaves'); 
    } 
} 

用户模式:

class User extends Model implements AuthenticatableContract, 
            AuthorizableContract, 
            CanResetPasswordContract 
{ 
    use Authenticatable, Authorizable, CanResetPassword; 

    protected $table = 'users'; 

    protected $fillable = ['name', 'email', 'password']; 

    protected $hidden = ['password', 'remember_token']; 

    public function Leaves() 
    { 
     return $this->hasMany('App\Leaves'); 
    } 

} 
1
Leave模型

你会

function type() { 
    return $this->hasOne(App\LeaveType); 
} 
在LeaveType

,你应该回报

function leave() { 
    return $this->belongsToMany(App\LeaveType); 
} 

,并在你的控制器:

$user = User::oldest('name')->with('leave', 'leave.type')->get(); 
dd($user->leave->type); 
+0

还注意到' - > leave'和' - > type'在获取属性时缺少'()'。 '休假()'会返回一个查询生成器,所以你可以做'$用户>离开() - >创建($假);' –

+0

我似乎对功能型)问题( 有什么毛病我外键引用?从附件中,Leaves表中的leave_type是对leave_type表的外部引用 – Derrick

+0

我错过了,对不起,laravel的默认值是'model_name_id'。在你的情况下,这将是'leave_type_id',但你可以覆盖它。语法是'return $ this-> hasOne('App \ Model_Name','foreign_key','local_key');' –