根据屏幕截图和模型设置,有没有人能根据我的雄辩关系提出建议?
模型设置:
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');
}
}
目前我只能获取树叶细节,但需要根据
检索leave_type的type_name$user = User::oldest('name')->get();
foreach ($users as $user) {
$user->leave()-get();
}
答案 0 :(得分: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);
答案 1 :(得分:0)
离开模型:
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');
}
}