Laravel 5雄辩的关系 - 虽然有很多

时间:2015-05-20 03:45:39

标签: eloquent laravel-5

我有三种型号。

  • 研究
  • 网站
  • 单元

研究拥有并属于许多站点,并且属于Study的每个站点都具有并属于许多单元。请参阅下图。

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

我如何使用Laravel 5 Eloquent Relationships实现这一目标。

2 个答案:

答案 0 :(得分:2)

听起来你在Study-> Site和Site-> Unit之间有多对多的关系。您可以阅读有关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.

答案 1 :(得分:0)

你必须根据你的图表创建3个模型的学习,站点和单元研究有很多站点和站点有很多单元,在你的图表研究中没有与单位直接关系你的雄辩模型将是这样的。

class Study extends Model {
    public function sites(){
        return $this->hasMany('App\Site');
    }
}

class Site extends Model {

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

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

}

class Unit extends Model {

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

}