照亮 - HasMany - 迭代

Illuminate - HasMany - Iteration


我只是在我目前手工制作的数据库和网站上用 Illuminate (Laravel) 做我的第一个练习。我想通过使用 MVC 进行改进,并发现 Illuminate 很有趣,可用于与我的数据库进行交互。

我花了一天时间研究这个该死的小代码,但找不到问题所在,我希望有人对我有好主意。非常感谢!

基本问题:为什么我不能遍历给定学期的课程?虽然可以调用特定课程。

use Illuminate\Database\Eloquent\Model as Eloquent;

class Semester extends Eloquent {
    protected $table      = "tblSemester";
    protected $primaryKey = "SemesterID";

    public function getCourses() {
        // test if semester is correct
        echo $this->SemesterID, " - ", $this->Semestertext, "<br>"; 

        // This works fine and returns the expected result
        $course = $this->hasMany('Course', 'Semester')->first();
        echo $course->Number, " - ", $course->Title;

        // This doesn't work. It returns nothing. 
        // There seems to be no data in $courses (just metadata)
        $courses = $this->hasMany('Course', 'Semester');
        foreach ($courses as $course) {
            echo $course->Number, " - ", $course->Title;
            echo "<br>";
        }

        return "<h1>" . "Test ends" . "</h1>";
    }
}

非常感谢! 蒂姆

首先

既然你说你是'Laravel'新手,想跟进MVC,我想我可以给你一些建议。

  1. 在 laravel 模型中,不包含数据库操作代码。而是将它们写在控制器中。
  2. 在模型中,只包含属于单个模型实例的函数(非静态函数)。
    1. 关系
    2. 查询范围
    3. 访问器/修饰符

示例模型

class Semester extends Model 
{
    protected $table = 'semesters';

    // relationships
    public function cources()
    {
        return $this->hasMany(Cource::class);
    }
}

示例控制器

class SemesterController extends Controller
{
    public function iterateOverCourcesOfGivenSemester()
    {
        // take first semester as an example.
        $givenSemester = Semester::first();

        // all the cources belongs to a given semester.
        $cources = $givenSemester->cources;

        foreach($cources as $cource) {

            // Warning! don't echo anything in a controller, Instead return them to a view.
            echo $course->Number, " - ", $course->Title;
            echo "<br>";
        }
    }
}

为什么这不起作用:

public function cources()
{
    return $this->hasMany(Cource::class);
}   

但是这样做:

public function cources()
{
    return $this->hasMany('Course', 'Semester')->get();
}