Laravel 5.5关于模型

时间:2020-03-01 13:37:50

标签: javascript laravel laravel-5

我想要一个Chapter模型,其中包含一个区列,其中包含多个区模型。 但是我不知道如何链接它。我刚刚完成了模型和迁移。

public class ClientMessage
{
    public event Func<Task> MsgChange;

    public ClientMessage(string msg, EMsgType msgType)
    {
        this.Message = msg;
        this.MsgType = msgType;
        NotifyStateChanged();
    }

    public void SetMsg(string msg, EMsgType msgType)
    {
        this.Message = msg;
        this.MsgType = msgType;
        NotifyStateChanged();
    }

    public string Message { get; set; }

    public EMsgType MsgType { get; set; }

    private void NotifyStateChanged()
    {
        if (MsgChange != null)
        {
            MsgChange.Invoke();
        }
    }
}

class Chapter extends Model
{
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable = [
      'name',
  ];

  public function districts()
  {
    return $this->hasMany(District::class);
  }
}

此后我该怎么办?我需要在迁移文件一章中提及地区吗?

这是我的迁移文件。

class District extends Model
{
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable = [
      'name',
  ];

  public function chapter()
  {
      return $this->belongsTo(Chapter::class);
  }
  
  public function blocks()
  {
    return $this->hasMany(Block::class);
  }
}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateChaptersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('chapters', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->indexed();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('chapters');
    }
}

我需要在$ fillable侧链接它们吗?

1 个答案:

答案 0 :(得分:0)

您需要使用数据结构链接它们,以便Laravel Eloquent Relation可以利用此优势。见下文。

首先,请确保您的数据库结构具有相关的属性。例如。您的迁移看起来应该与此类似

class CreateDistrictsTable extends Migration
{
public function up()
    {
        Schema::create('districts', function (Blueprint $table) {
            $table->increments('id');
            // all district related coloumns

            $table->unsignedBigInteger('chapter_id');
            $table->timestamps();

        });
    }
}

chapter_id表中的districts列用作外键约束,并连接特定章下的所有区。

Chapter类中,您需要定义如下所示的关系(已完成):

public function districts()
{
        return $this->hasMany(District::class);
}

然后,您可以通过调用districts()方法来检索给定章节的所有区。例如,要获取chapter Id = 1的所有地区,可以执行以下操作:

App\Chapter::find(1)->districts
相关问题