eloquent - Laravel 5 Eloquent 关系 - 有很多想法

标签 eloquent laravel-5

我有三个模型。

  • 学习
  • 网站
  • 单位

研究具有并属于许多站点,并且属于研究的每个站点又具有并属于许多单元。请看下图。

http://tinypic.com/r/ojhx0g/8

我如何使用 Laravel 5 Eloquent 关系来实现这一目标。

最佳答案

听起来“研究”->“站点”和“站点”->“单元”之间存在多对多关系。您可以阅读有关 many-to-many relationships here. 的 Laravel 文档

型号

以下是 Eloquent 识别关系所需的相关函数。

class Study extends Model {
    // If you named your table differently (like 'studies'), specify that here
    protected $table = 'studys';

    // This assumes a pivot table named 'site_study', if you named yours
    // differently you can pass in into the belongsToMany() function as the
    // second parameter.
    public function sites() {
        return $this->belongsToMany('App\Site');
    }
}

class Site extends Model {
    protected $table = 'sites';

    public function studies() {
        return $this->belongsToMany('App\Study');
    }

    public function units() {
        return $this->belongsToMany('App\Unit');
    }
}

class Unit extends Model {
    protected $table = 'units';

    public function sites() {
        return $this->belongsToMany('App\Site');
    }
}

然后,要访问属于研究的站点,您可以执行以下操作:

$sites = Study::find(1)->sites;

数据透视表迁移

Laravel 希望数据透视表的命名类似于 'alpha_beta',其中 alphabeta单一模型名称按字母顺序排列。因此,数据透视表的迁移将如下所示:

class CreateSiteStudyTable extends Migration {
    public function up() {
        Schema::create('site_study', function(Blueprint $table)) {
            $table->integer('site_id')->unsigned();
            $table->foreign('site_id')->references('id')->on('sites');
            $table->integer('study_id')->unsigned();
            $table->foreign('study_id')->references('id')->on('studys'); // or whatever you named it
            $table->unique(['site_id', 'study_id']);
            $table->timestamps();
        });
    }

    public function down() {
        Schema::drop('site_study');
    }
}

class CreateSiteUnitTable extends Migration {
    public function up() {
        Schema::create('site_unit', function(Blueprint $table)) {
            $table->integer('site_id')->unsigned();
            $table->foreign('site_id')->references('id')->on('sites');
            $table->integer('unit_id')->unsigned();
            $table->foreign('unit_id')->references('id')->on('units');
            $table->unique(['site_id', 'unit_id']);
            $table->timestamps();
        });
    }

    public function down() {
        Schema::drop('site_unit');
    }
}

您可以阅读 Foreign Keys in Laravel here.

关于eloquent - Laravel 5 Eloquent 关系 - 有很多想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339907/

相关文章:

javascript - 资源解释为文档,但使用 MIME 类型 application/json,laravel 进行传输

mysql - Eloquent ORM,deleted_at 使用软删除时没有索引

php - 拉维尔 : How to count in query

php - 使用 Laravel 5 intervention image 为图像添加空白以制作正方形图像

laravel - Laravel 中的 Eloquent 关系

php - Laravel 5 - 发送群组电子邮件

php - 如何对 Eloquent 子查询进行排序

laravel - 在Laravel中向Eloquent模型添加自定义方法

php - 具有两个主键更新的 Laravel 模型

拉拉维尔 5 : Change default maintenance (503) view path