简体   繁体   English

Laravel多级关系

[英]Laravel multi level relationship

I want to create view that will show class_meets information for additional information I want to show subject name from table subjects already trying hasOneTrough, hasManyTrough and belongsToMany but it's like the function only show from subjects to class_meets, whereas what I need is the opposite我想创建将显示 class_meets 信息以获取其他信息的视图 我想从已经尝试 hasOneTrough、hasManyTrough 和 belongsToMany 的表中显示主题名称,但这就像 function 仅显示从主题到 class_meets,而我需要的是相反

Want to add some function on ClassMeet Model想在 ClassMeet Model 上添加一些 function

Here's from my Listing model:以下是我的清单 model:

  • Subject主题
class Subject extends Model
{
    use SoftDeletes;
    public $table = 'subjects';
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
    protected $fillable = [
        'subject_name'
    ];
}
  • Routine常规
class Routine extends Model
{
    use SoftDeletes;
    public $table = 'routines';
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
    protected $fillable = [
        'academic_year_id',
        'subject_id',
        'classes_id'
        'day',
        'start_time',
        'end_time',
    ];
}
  • ClassMeet课堂聚会
class ClassMeet extends Model
{
    use SoftDeletes;
    public $table = 'class_meets';
    protected $dates = ['created_at', 'updated_at', 'deleted_at', 'date'];
    protected $fillable = [
        'routine_id',
        'date'
    ];
}

hasOneTrough, hasManyTrough won't work in this case. hasOneTrough, hasManyTrough 在这种情况下不起作用。

You need to add belongsTo relation to ClassMeet , Routine .您需要将 belongsTo 关系添加到ClassMeetRoutine

class ClassMeet extends Model
{
    use SoftDeletes;
    public $table = 'class_meets';
    protected $dates = ['created_at', 'updated_at', 'deleted_at', 'date'];
    protected $fillable = [
        'routine_id',
        'date'
    ];

    public routine(){
         return $this->belongsTo('App\Routine','routine_id','id')
    }
}

Routine Model be like例程 Model 就像

class Routine extends Model
{
    use SoftDeletes;
    public $table = 'routines';
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
    protected $fillable = [
        'academic_year_id',
        'subject_id',
        'classes_id'
        'day',
        'start_time',
        'end_time',
    ];
     public subject(){
         return $this->belongsTo('App\Subject','subject_id','id')
     }
}

Now you can get the subject with routine.现在您可以通过常规获得主题。

ClassMeet::with('routine.subject')->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM