Eloquent模型中關于hasMany和blongsTo的外鍵設置的解析

laravel中Eloquent模型是一種面向對象的對數據庫的封裝,里面定義了<code>hasOne\hasMany</code>與其對應的<code>belongsTo</code>,還有最后就是多對多關系的belongsToMany。表面的意思很簡單,一個一個來說。

hasMany

這個最好理解,就是一個<code>用戶</code>對應一篇<code>文章</code>。
<code>hasOne</code>是一種獲取方式,獲取對應的一個內容。

class User extend Model{
    publi funtion article(){
        return $this->hasOne('Article');
    }
}

然后在控制器controller里可以這樣使用。

class Acontroller extend Controller{
    public funtion index(){
        $article=User::find(1)->article();
    }
}

這里就不細說了,別的用發很類似,具體可以看官方文檔,這樣可以明白。這里主要通過一個例子來解釋一個,如果使用里面的外鍵功能,hasOne\hasMany\BelongsTo都有定義外鍵的功能。首先hasOne\hasMany\BelongsTo都有默認定義外鍵的功能。下面通過一個例子說明。
Client.php

nameSpace App;
use Illuminate\Database\Eloquent\Model;
class Client extend Model{
    protected $fillable=['name','company_name','vat','email','address','zipcode','city','primary_number','secondary_number','industry_id','company_type','fk_user_id'];
    public funtion userAssignee(){
        return $this->belongsTo('App\User','fk_user_id','id');
    }
  
    public funtion alltask(){
        return $this->hasMany('App\Tasks','fk_client_id','id')->orderBy('status','asc')->orderBy('created_at', 'desc');
    }
    public funtion allleads(){
        return $this->hasMany('App\Leads','fk_client_id','id')->orderBy('status', 'asc')->orderBy('created_at', 'desc');
    }
}

Leads.php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon;
class Leads extends Model{
      protected $fillable = [    'title',    'note',    'status',    'fk_user_id_assign',    'fk_user_id_created',    'fk_client_id',    'contact_date',    ];
      protected $dates = ['contact_date'];
      protected $hidden = ['remember_token'];
      public function clientAssignee(){
                return $this->belongsTo('App\Client', 'fk_client_id');
      }
      public function notes(){
              return $this->hasMany('App\Note', 'fk_lead_id', 'id');
      }
}

首先先看Client.php里面的allleads方法,里面用到了<code>$this->hasMany('App\Leads','fk_client_id','id')</code>,這里的內容指定是調用App\Leads中的fk_client_id外鍵,如果不指定就會調用默認的<code>Client_id</code>這個外鍵,所以調用默認外鍵的規律就是:本類名+id,但是這個外鍵在被調用的這個類(App\Leads)上。如果指明外鍵,那就不用默認外鍵了,但是這個這個外鍵依然在被調用的類上。下面看看Leads的數據遷移部分就知道了。

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

class CreateLeadsTable extends Migration{
     public function up()
    {
        Schema::create('leads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('note');
            $table->integer('status');
            $table->integer('fk_user_id_assign')->unsigned();
            $table->foreign('fk_user_id_assign')->references('id')->on('users');
            $table->integer('fk_client_id')->unsigned();
            $table->foreign('fk_client_id')->references('id')->on('clients');
            $table->integer('fk_user_id_created')->unsigned();
            $table->foreign('fk_user_id_created')->references('id')->on('users');
            $table->datetime('contact_date');
            $table->timestamps();
        });
    }
}

在Lead的表創建過程中,明確指定了Lead的外鍵fk_client_id關聯的是clients類的id屬性,這樣就串起來了吧。如果使用自定義的外鍵,那就在被調用(leads)的時候,告訴調用者(clients),具體是哪個外鍵(fk_client_id)。

belongsTo

belongsTo外鍵的使用剛好和hasMany反過來,看Client.php的userAssignee方法,里面用到了belongsTo方法,使用的外鍵是fk_user_id,但這個外鍵是調用者的外鍵,即Client的內部定義的屬性,可以在fillable內看到,這樣就明確了,belongsTo里定義的外鍵是調用者(Client)內部定義外鍵,鏈接著被調用者(User)。下面是Client的遷移,可以看到是在調用者內部定義的外鍵。

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

class CreateClientsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
        
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->integer('primary_number');
            $table->integer('secondary_number');
            $table->string('address');
            $table->integer('zipcode');
            $table->string('city');
            $table->string('company_name');
            $table->integer('vat');
            $table->string('industry');
            $table->string('company_type');
            $table->integer('fk_user_id')->unsigned();
            $table->foreign('fk_user_id')->references('id')->on('users');
            $table->integer('industry_id')->unsigned();
            $table->foreign('industry_id')->references('id')->on('industries');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::drop('clients');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容