Laravel5.1 模型 --远层一对多关系

远层一对多我们可以通过一个例子来充分的了解它:

每一篇文章都肯定有并且只有一个发布者 发布者可以有多篇文章,这是一个一对多的关系。一个发布者可以来自于一个国家 但是一个国家可以有多个发布者,这又是一个一对多关系,那么 这其中存在一个远层的一对多就是"国家和文章的关系"。国家表可以通过发布者表远层关联到文章表。


 1 实现远层一对多关系

 1.1 文章表结构

    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->integer('user_id');
            $table->timestamps();
        });
    }

 1.2 在users表中添加一列

    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->integer('country_id');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('country_id');
        });
    }

 1.3 国家表结构

    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

 1.4 编写一对多关系

首先是Country和User的关系:

Country模型:

    public function users()
    {
        return $this->hasMany(User::class);
    }

User模型:

    public function country()
    {
        return $this->belongsTo(Country::class);
    }

然后是User和Article的关系:

User模型:

    public function articles()
    {
        return $this->hasMany(Article::class);
    }

Article模型:

    public function user()
    {
        return $this->belongsTo(User::class);
    }

 1.5 访问远程一对多关系

这是今天的主要内容,实现Country可远层查找到Article:

    public function articles()
    {
        /**
         * 建议第一个和第二个参数写全,第三个第四个参数可省略使用默认(如果默认的没问题)。
         */
        return $this->hasManyThrough(Article::class, User::class, 'country_id', 'user_id');
    }