我有三个模型。
- 学习
- 网站
- 单位
研究具有并属于许多站点,并且属于研究的每个站点又具有并属于许多单元。请看下图。
我如何使用 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'
,其中 alpha
和 beta
是单一模型名称按字母顺序排列。因此,数据透视表的迁移将如下所示:
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');
}
}
关于eloquent - Laravel 5 Eloquent 关系 - 有很多想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339907/