如何在Laravel模型中获取模块的部门名称

时间:2015-02-05 12:27:54

标签: php laravel models

我试图让部门认为模块是laravel的一部分,如:

这是我的教师课程:

    <?php
class Faculty extends Eloquent {
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'faculty';
    public $timestamps = false;
    /**
     * Whitelisted model properties for mass assignment.
     *
     * @var array
     */
    protected $primaryKey='facultyid';

    protected $fillable = array('facultyname', 'facultyshort');

    public function departments()
    {
        return $this->hasMany('Departments', 'facultyid');
    }
}

这是我的部门课程

    <?php
class Departments extends Eloquent {
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'departments';

    public $timestamps = false;
    /**
     * Whitelisted model properties for mass assignment.
     *
     * @var array
     */
    protected $primaryKey='departmentid';
    protected $foreignKey='facultyid';

    protected $fillable = array('departmentname', 'departmenthead', 'facultyid');

    public function modules()
    {
        return $this->hasMany('Modules', 'departmentid');
    }
    public function faculty()
    {
        return $this->belongsTo('Faculty', 'facultyid');
    }
}

最后这是我的模块类:

<?php
class Modules extends Eloquent {
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'modules';
    protected $foreignKey='departmentid';
    public $timestamps = false;
    /**
     * Whitelisted model properties for mass assignment.
     *
     * @var array
     */
    protected $primaryKey='mid';

    protected $fillable = array('mfulltitle', 'mshorttitle', 'mcode', 
        'mcrn', 'mfieldofstudy', 'mcoordinator','mlevel', 
        'mcredits', 'melective', 'departmentid');

    public function department()
    {
        return $this->belongsTo('Departments', 'departmentid');
    }

    public function classes()
    {
        return $this->hasMany('Classes', 'moduleid')->orderBy('classid', 'ASC');
    }
}

我尝试过这样的事情:

@foreach(Modules::where('melective', '=', 1)->get() as $mod)
        {{$mod->mshorttitle}} belongs to department: {{ $mod->department->departmentname }}
    @endforeach

但它不起作用,有没有人知道如何做到这一点?

==============================

经过一番工作后,我想出来了

在Department类中我添加了以下函数:

public function name()
{
    return $this->departmentname;
}

我将代码更改为以下内容:

@foreach(Modules::where('melective', '=', 1)->get() as $mod)
    {{$mod->mshorttitle}} belongs to department: {{ $mod->department->name() }}
@endforeach

0 个答案:

没有答案